设计模式c++实现:装饰(Decorator)模式
Posted skyman_2001
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式c++实现:装饰(Decorator)模式相关的知识,希望对你有一定的参考价值。
转载请注明,来自:http://blog.csdn.net/skyman_2001
class Component
public:
Component()
virtual ~Component()
virtual void operation() = 0;
virtual Component *remove() = 0;
;
class ConcreteComponent: public Component
public:
ConcreteComponent()
~ConcreteComponent()
void operation()
std::cout <<"Concrete component operation"<< std::endl;
Component *remove()
return this;
;
class Decorator : public Component
public:
Decorator(Component *comp) : m_component(comp)
virtual ~Decorator()
virtual void operation()
m_component->operation();
Component *remove()
return m_component;
private:
Component *m_component;
;
class Decor1: public Decorator
public:
Decor1(Component *comp) : Decorator(comp)
virtual ~Decor1()
virtual void operation()
Decorator::operation();
addedBehavior();
private:
void addedBehavior()
std::cout << "Decor1 addedBehavior" << std::endl;
;
class Decor2: public Decorator
public:
Decor2(Component *comp) : Decorator(comp)
virtual ~Decor2()
virtual void operation()
Decorator::operation();
addedBehavior();
private:
void addedBehavior()
std::cout << "Decor2 addedBehavior" << std::endl;
;
int _tmain(int argc, _TCHAR* argv[])
Component* concrete = new ConcreteComponent();
Component* decored1 = new Decor1(concrete);
Component* decored2 = new Decor2(decored1);
decored2->operation();
cout << "---------------" << endl;
Component* temp = decored2->remove();
temp->operation();
cout << "---------------" << endl;
temp = temp->remove();
temp->operation();
cout << "---------------" << endl;
temp = temp->remove();
temp->operation();
delete decored2;
delete decored1;
delete concrete;
return 0;
运行结果:
Concrete component operation
Decor1 addedBehavior
Decor2 addedBehavior
---------------
Concrete component operation
Decor1 addedBehavior
---------------
Concrete component operation
---------------
Concrete component operation
以上是关于设计模式c++实现:装饰(Decorator)模式的主要内容,如果未能解决你的问题,请参考以下文章