时间:2021-01-14 11:14:21 | 栏目:C代码 | 点击:次
装饰模式是一种经典的类功能扩展模式,其精髓在装饰类使用继承加聚合的方式获得接口和要实现对象,然后通过自己实现扩展接口
作用
装饰模式通过装饰类动态地将责任附加到对象上,若要扩展功能,无需通过继承增加子类就能扩展对象的新功能,提供了比继承更有弹性的替代方案,避免了子类数量膨胀带来的系统臃肿。
类视图
代码实现
class Component { public: Component(){} virtual ~Component(){} virtual void operation() = 0; }; class ConcreteComponentA : public Component { public: ConcreteComponentA(){} ~ConcreteComponentA(){} void operation() { fprintf(stderr, "ConcreteComponentA's operation!\n"); } }; class ConcreteComponentB : public Component { public: ConcreteComponentB(){} ~ConcreteComponentB(){} void operation() { fprintf(stderr, "ConcreteComponentB's operation!\n"); } }; class Decorator : public Component { public: Decorator() :mComponent(NULL){} virtual ~Decorator(){} virtual void operation() { if (mComponent) mComponent->operation(); } virtual void setComponent(Component* pComponent) { mComponent = pComponent; } protected: Component* mComponent; }; class ConcreteDecoratorE : public Decorator { public: ConcreteDecoratorE (); virtual ~ConcreteDecoratorE (); virtual void addBehavior() { mComponent->operation(); fprintf(stderr, "ConcreteDecoratorE's addBehavior!\n"); } }; class ConcreteDecoratorF : public Decorator { public: ConcreteDecoratorF (); virtual ~ConcreteDecoratorF (); virtual void addBehavior() { operation(); fprintf(stderr, "ConcreteDecoratorF's addBehavior!\n"); } }; int main() { ConcreteComponentB *pComponent = new ConcreteComponentB(); ConcreteDecoratorF decorator; decorator.setComponent(pComponent); decorator.addBehavior(); }