3 装饰模式(1)

装饰模式

 

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
1 #include < iostream >
2 #include < string >
3
4   using std:: string ;
5   using std::cout;
6   using std::endl;
7
8 class Component
9 {
10 public :
11 virtual void Operation() = 0 ;
12 };
13
14 class ConcreteComponent : public Component
15 {
16 public :
17 void Operation()
18 {
19 cout << " 具体对象的操作 " << endl;
20 }
21 };
22
23 // 装饰抽象类
24 class Decorator : public Component
25 {
26 public :
27 void SetComponent(Component * component)
28 {
29 this -> component = component;
30 }
31 void Operation()
32 {
33 component -> Operation();
34 }
35 private :
36 Component * component;
37 };
38
39 // 具体装饰类A
40 class ConcretorDecoratorA : public Decorator
41 {
42 public :
43 void Operation()
44 {
45 Decorator::Operation();
46 addedState = " new state " ;
47 cout << " 具体对象A的操作 " << endl;
48
49 }
50 private :
51 string addedState;
52 };
53
54 // 具体装饰类B
55 class ConcretorDecoratorB : public Decorator
56 {
57 public :
58 void Operation()
59 {
60 Decorator::Operation();
61 AddedBehavior();
62 cout << " 具体对象B的操作 " << endl;
63 }
64 void AddedBehavior()
65 {
66 cout << " 具体装饰类B新增加的功能 " << endl;
67 }
68 };
69
70 int main()
71 {
72 // 客户端实现
73 ConcreteComponent * c = new ConcreteComponent();
74 ConcretorDecoratorA * pa = new ConcretorDecoratorA();
75 ConcretorDecoratorB * pb = new ConcretorDecoratorB();
76
77 pa -> SetComponent(c);
78 pb -> SetComponent(pa);
79 pb -> Operation();
80 return 0 ;
81 }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值