尴尬的OOP:在不同的类上继承相同的方法吗? [英] Awkward OOP: Same method on different classes not inherited?

查看:65
本文介绍了尴尬的OOP:在不同的类上继承相同的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是交易: 我有两个不同类的对象,分别是DataSizeActionDataColorAction.这些类的共同祖先EncoderAction不在链中.

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.

这两个对象都公开了一个称为setScale(int scale)的方法,该方法为其执行的编码设置缩放比例类型.在两种情况下,该方法都做同样的事情.

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.

但是,该方法在任何共同祖先中都不存在(顺便说一句,该OO是我正在使用的库,并且设计不由我自己决定).

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).

我想编写一个采用DataSizeAction或DataColorAction并在该对象上调用setScale的方法.

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

我的问题是:在我用instanceof强行强行处理单独的案件之前,有没有更优雅的方式来解决这个问题?

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

谢谢!

推荐答案

可以将接口添加到层次结构中吗?

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);
   }
}

这篇关于尴尬的OOP:在不同的类上继承相同的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆