目的:为其他对象提供一种代理以控制对这个对象的访问
理解:尽管Decorator的实现部分与代理相似,但Decorator的目的不一样。Decorator为对象添加一个或多个功能,而代理则控制对对象的访问
例子:
class Print //统一接口 { public: virtual void show() = 0; }; class StringPrint: public Print //被代理的类 { string str; public: StringPrint(string str) { this->str = str; } void show() { cout << str << endl; } }; class ProxyPrint: public Print //代理类 { StringPrint* strp; public: ProxyPrint(StringPrint* strp) { this->strp = strp; } void show() //这里可以提供控制访问 { strp->show(); } };
int main() { ProxyPrint* pp = new ProxyPrint(new StringPrint("hello world!")); pp->show(); delete pp; return 0; }