Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 面向对象-继承与装饰问题_Oop - Fatal编程技术网

Oop 面向对象-继承与装饰问题

Oop 面向对象-继承与装饰问题,oop,Oop,我有一个与OOP相关的问题。我有一个界面,比如: class MyInterface { public int getValue(); } 在我的项目中,此接口由7个实现实现实现: class MyImplementation1 implements MyInterface { ... } ... class MyImplementation7 implements MyInterface { ... } 这些实现由几个不同的模块使用。对于某些模块,必须稍微调整MyInterface

我有一个与OOP相关的问题。我有一个界面,比如:

class MyInterface {
    public int getValue();
}
在我的项目中,此接口由7个实现实现实现:

class MyImplementation1 implements MyInterface { ... }
...
class MyImplementation7 implements MyInterface { ... }
这些实现由几个不同的模块使用。对于某些模块,必须稍微调整MyInterface的行为。让我们假设它必须返回实现者+1的值(为了示例)。我通过创建一个小装饰器解决了这个问题:

class MyDifferentInterface implements MyInterface {
   private MyInterface i;

   public MyDifferentInterface(MyInterface i) {
       this.i = i;
   }

   public int getValue() {
       return i.getValue() + 1;
   }
}
这就行了

我的问题是:其中一个模块不接受MyInterface参数,而是直接接受MyImplementation4。这是因为此模块需要MyImplementation4的特定行为,而接口MyInterface本身不包含这些行为。但是,困难来了,这个模块还必须在MyImplementation4的修改版本上工作。也就是说,getValue()必须返回+1

解决这个问题的最好办法是什么?我没能想出一个不包含大量重复代码的解决方案

请注意,尽管上面的示例非常小和简单,但是界面和装饰器非常大和复杂


非常感谢大家。

MyImplementation4
中使用
virtual
关键字声明
getValue


MyImplementation4
继承一个新类,并使用
override
关键字声明
getValue
函数,并将其实现为
return base.getValue()+1
如果它是Java语言,则可以执行以下操作

class ModifiedMyImplementation4 extends MyImplementation4
{
    @Override
    public int getValue()
    {
        return super.getValue() + 1;
    }
}

没有代码重复

您可以尝试以下方法:

public class MyDifferentImplementation4 extends MyImplementation4 {
    private MyDifferentInterface mdi;
    public MyDifferentImplementation4(MyDifferentInterface mdi) {
        this.mdi = mdi;
    }
    public getValue() {
        return mdi.getValue();
    }
}
传递给构造函数的MyDifferentInterface实例应该封装MyImplementation4的实例(您可以通过使用MyDifferentInterface的子类来强制实现,该子类的构造函数采用MyImplementation4的实例,而不是接口)

这个解决方案意味着我必须 复制所有这些代码

您不能将要复制的代码放入抽象类
MyAbstractImplementation
?然后这两个子类可以从抽象类继承。它所需要的只是一个单一的抽象方法,它甚至不需要做任何事情,只需要由孩子们来实现

void foo(void)


需要不同行为的子对象将重写该方法。使用者需要接受
MyAbstractImplementation
类型而不是接口。瞧,没有代码重复。

谢谢你的回答。装饰器MyDifferentInterface非常复杂,包含大量代码。这个解决方案意味着我必须复制所有这些代码。OP使用Java语法;Java没有
virtual
关键字(默认情况下方法是虚拟的!)为什么不能声明一个继承
MyImplementation4
的新类,并只覆盖必须更改其返回值的方法?对我来说,这听起来很直接。+1当然,最好的选择是修复其他模块的设计,但这可能不可能。+1,或者如果你不想继承,将
MyImplementation4
的实例传递到构造函数中,并将未更改的操作委托给该实例。或者只需向MyImplementation4添加一个开关,如果设置为true,则会将getValue()的返回值增加1。