C++设计模式之装饰模式(Decorator)

时间:2022-11-13 22:19:03

装饰模式是一种经典的类功能扩展模式,其精髓在装饰类使用继承加聚合的方式获得接口和要实现对象,然后通过自己实现扩展接口

作用
装饰模式通过装饰类动态地将责任附加到对象上,若要扩展功能,无需通过继承增加子类就能扩展对象的新功能,提供了比继承更有弹性的替代方案,避免了子类数量膨胀带来的系统臃肿。

类视图

C++设计模式之装饰模式(Decorator)

代码实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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();
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/chencarl/p/8649394.html