饰模式:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。有时我们希望给某个对象而不是整个类添加一些功能。比如有一个手机,允许你为手机添加特性,比如增加挂件、屏幕贴膜等。一种灵活的设计方式是,将手机嵌入到另一对象中,由这个对象完成特性的添加,我们称这个嵌入的对象为装饰。这个装饰与它所装饰的组件接口一致,因此它对使用该组件的客户透明。
具体代码:
1 // decoratortest.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <string> 7 using namespace std; 8 9 10 class Phone 11 12 { 13 14 public: 15 Phone() {} 16 17 virtual ~Phone() {} 18 19 virtual void ShowDecorate() {} 20 21 }; 22 23 class iPhone : public Phone 24 25 { 26 27 private: 28 29 string m_name; //手机名称 30 31 public: 32 33 iPhone(string name): m_name(name){} 34 35 ~iPhone() {} 36 37 void ShowDecorate() { cout<<m_name<<"的装饰"<<endl;} 38 39 }; 40 41 //具体的手机类 42 43 class NokiaPhone : public Phone 44 45 { 46 47 private: 48 49 string m_name; 50 51 public: 52 53 NokiaPhone(string name): m_name(name){} 54 55 ~NokiaPhone() {} 56 57 void ShowDecorate() { cout<<m_name<<"的装饰"<<endl;} 58 59 }; 60 61 //装饰类 62 63 class DecoratorPhone : public Phone 64 65 { 66 67 private: 68 69 Phone *m_phone; //要装饰的手机 70 71 public: 72 73 DecoratorPhone(Phone *phone): m_phone(phone) {} 74 75 virtual void ShowDecorate() { m_phone->ShowDecorate(); } 76 77 }; 78 79 //具体的装饰类 80 81 class DecoratorPhoneA : public DecoratorPhone 82 83 { 84 85 public: 86 87 DecoratorPhoneA(Phone *phone) : DecoratorPhone(phone) {} 88 89 void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); } 90 91 private: 92 93 void AddDecorate() { cout<<"增加挂件"<<endl; } //增加的装饰 94 95 }; 96 97 //具体的装饰类 98 99 class DecoratorPhoneB : public DecoratorPhone 100 101 { 102 103 public: 104 105 DecoratorPhoneB(Phone *phone) : DecoratorPhone(phone) {} 106 107 void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); } 108 109 private: 110 111 void AddDecorate() { cout<<"屏幕贴膜"<<endl; } //增加的装饰 112 113 }; 114 115 int _tmain(int argc, _TCHAR* argv[]) 116 { 117 cout<<"装饰模式"<<endl; 118 119 Phone *iphone = new NokiaPhone("6300"); 120 121 Phone *dpa = new DecoratorPhoneA(iphone); //装饰,增加挂件 122 123 Phone *dpb = new DecoratorPhoneB(dpa); //装饰,屏幕贴膜 124 125 dpb->ShowDecorate(); 126 127 delete dpa; 128 129 delete dpb; 130 131 delete iphone; 132 system("pause"); 133 return 0; 134 }