标签:c++ 设计模式
#include "stdafx.h" #include <iostream> #include <memory> using namespace std; class Component { public: virtual void Operation() = 0; }; class ConcreteComponent :public Component { virtual void Operation() { cout << "具体对象的操作!" << endl; } }; class Decorator :public Component { private: shared_ptr<Component > _pComponent; protected: shared_ptr<Component > GetComponent() { return _pComponent; } public: void SetComponent( shared_ptr<Component > pComponent ) { _pComponent = pComponent; } virtual void Operation() { if (_pComponent != NULL) { _pComponent->Operation(); } } }; class ConcreteDecorator1 :public Decorator { public: virtual void Operation() { //首先运行原Component的方法,再运行本类的方法 GetComponent()->Operation(); cout << "具体装饰对象ConcreteDecorator1" << endl; } }; class ConcreteDecorator2 :public Decorator { public: virtual void Operation() { GetComponent()->Operation(); cout << "具体装饰对象ConcreteDecorator2" << endl; } };
// DecorateMethod.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Decorator.h" int _tmain (int argc , _TCHAR * argv []) { //装饰的方法是,首先建造ConcreteComponent对象, //然后建造ConcreteDecorator1来装饰ConcreteComponent //借助智能指针来实现. //最后执行的是最后的装饰类的Operation shared_ptr<ConcreteComponent > pConcreteComponent(new ConcreteComponent); shared_ptr<ConcreteDecorator1 > pConcreteDecorator1(new ConcreteDecorator1); pConcreteDecorator1->SetComponent(pConcreteComponent); pConcreteDecorator1->Operation(); std::cout << std::endl; shared_ptr<ConcreteDecorator2 > pConcreteDecorator2(new ConcreteDecorator2); pConcreteDecorator2->SetComponent(pConcreteDecorator1); pConcreteDecorator2->Operation(); getchar(); return 0; }
标签:c++ 设计模式
原文地址:http://blog.csdn.net/wwwdongzi/article/details/26288907