在Decorator模式中,抽象类实现接口,具体类(Decorator)扩展抽象类。如果具体类直接实现接口,而不是通过抽象类继承接口,那么模式的功能会发生什么?
发布于 2021-04-24 11:11:28
抽象类不是必需的。从GoF书的第179页开始,
当你只需要添加一个职责时,不需要定义一个抽象的装饰器类。当您处理现有的类层次结构而不是设计新的类层次结构时,通常会出现这种情况。在这种情况下,您可以将Decorator向组件转发请求的职责合并到ConcreteDecorator中。
Head First Design的一个类似问题是,What is the reason for moving the instance variable into an abstract class in the decorator pattern?
发布于 2021-04-24 14:41:09
最初的设计模式书(GoF)是1994年出版的,它使用了C++和SmallTalk作为例子。IIRC,C++没有语言级别的接口(至少在1994年没有)。当这本书告诫
程序指向接口,而不是实现
您应该将界面解释为一个概念,而不是一种语言构造。
例如,在C++中,用专门定义纯虚函数的抽象类来模拟接口是很常见的。GoF一书中的许多C++示例都是这样做的。
有一个strong relationship between abstract classes and interfaces,在这一点上它们实际上是可互换的。
至于装饰器模式,我猜想装饰一个接口总是可能的。例如,考虑如下所示的接口:
public interface IFace
{
void Command(Arg1 arg1, Arg2 arg2);
Ret1 Query(Arg3);
}AFAICT,你总是可以写一个IFace的装饰器--至少是一个退化的装饰器:
public class MyFace : IFace
{
private readonly IFace inner;
public MyFace(IFace inner)
{
this.inner = inner;
}
public void Command(Arg1 arg1, Arg2 arg2)
{
// Consider doing something interesting here...
inner.Command(arg1, arg2);
// ... or here
}
public Ret1 Query(Arg3)
{
// Consider doing something interesting here...
Ret1 ret = inner.Query(arg3);
// ... or here
return ret;
}
}因此,无论您是使用抽象类还是使用接口,对Decorator模式都没有区别。
https://stackoverflow.com/questions/67236728
复制相似问题