Awkward OOP: Same method on different classes not

2019-06-25 14:35发布

问题:

Here's the deal: I have two objects of different classes, a DataSizeAction and a DataColorAction. The classes have a common ancestor EncoderAction not far up the chain.

Both these objects expose a method called setScale(int scale) which sets a scale type for the encoding they carry out. The method does the same thing in both cases.

However, the method is not present in any common ancestor (btw, this OO is a Library I'm using and the design is not up to my discretion).

I would like to write a method that takes either a DataSizeAction or DataColorAction and calls setScale on that object.

My question is: before I go brute-forcing the separate cases with instanceof, is there a more elegant way to handle this?

Thanks!

回答1:

Can you add interfaces to your hierarchy?

interface IScalable {
   void setScale(int scale);
   int getScale();
}

class DataSizeAction extends EncoderAction implements IScalable {
   ...
}

class SomeoneElse {
   private int scale = 2;

   public void setScale(IScalable scalable) {
      scalable.setScale(this.scale);
   }
}


回答2:

Try this:

  1. Make another class which extends EncoderAction
  2. Declare setScale as an abstract method within there
  3. Have DataSizeAction and DataColorAction extend your new class.

Now, you can write your code to refer to instances of the new base class and avoid calling instanceof checks.

NOTE: Even though what I have here should work, I would recommend Jonathon's answer. Since this is a gaurantee of functionality and doesn't have anything to do with your object's composition, interfaces are likely the way to go.