原例网址:装饰器模式(菜鸟教程)

装饰器模式

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。

 

1 #include "iostream"
 2 #include "string"
 3 using namespace std;
 4 
 5 
 6 
 7 //步骤1 创建一个接口
 8 class Shape
 9 {
10 public:
11     virtual void draw() = 0;
12 };
13 
14 
15 
16 //步骤2 创建实现接口的实体类
17 class Rectangle : public Shape
18 {
19 public:
20     void draw()
21     {
22         cout << "Shape: Rectangle" << endl;
23     };
24 };
25 
26 class Circle : public Shape
27 {
28 public:
29     void draw()
30     {
31         cout << "Shape: Circle" << endl;
32     };
33 };
34 
35 
36 
37 //步骤3 创建实现了 Shape 接口的抽象装饰类
38 class ShapeDecorator : public Shape
39 {
40 protected:
41     Shape* decoratedShape;
42 };
43 
44 
45 
46 //步骤4 创建扩展了 ShapeDecorator 类的实体装饰类
47 class RedShapeDecorator : public ShapeDecorator
48 {
49 public:
50     RedShapeDecorator(Shape* decoratedShape)    //构造函数
51     {
52         this->decoratedShape = decoratedShape;
53     }
54 
55     void draw() 
56     {
57         this->decoratedShape->draw();         
58         this->setRedBorder();
59     }
60 private:
61     void setRedBorder()
62     {
63         cout << "Border Color: Red" << endl;
64     }
65 };
66 
67 
68 
69 //步骤5 使用 RedShapeDecorator 来装饰 Shape 对象
70 void main()
71 {
72     Shape* circle = new Circle;
73     ShapeDecorator* redCircle = new RedShapeDecorator( new Circle );
74     ShapeDecorator* redRectangle = new RedShapeDecorator( new Rectangle );
75 
76     cout << "Circle with normal border" <<endl;
77     circle->draw();
78 
79     cout << "\nCircle of red border" <<endl;
80     redCircle->draw();
81 
82     cout << "\nRectangle of red border" <<endl;
83     redRectangle->draw();
84 
85 
86     delete circle;
87     delete redCircle;
88     delete redRectangle;
89 
90     system("pause");
91 }

 

运行结果:

java装饰模式模拟流 装饰模式实例_装饰器模式