装饰模式

装饰模式:

动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式通过把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需求选择地、按顺序地使用装饰功能包装对象。
装饰模式能够有效的把类的核心职责功能和装饰功能区分开,同时可以去除重复的装饰逻辑。

类图:

装饰模式_第1张图片

核心代码:

// ConcreteComponent.h
#include "Component.h"
#include 
using namespace std;
class ConcreteComponent : public Component
{
     

public:
	ConcreteComponent();
	virtual ~ConcreteComponent();
	void operation();
};
ConcreteComponent::ConcreteComponent(){
     

}

ConcreteComponent::~ConcreteComponent(){
     

}

void ConcreteComponent::operation(){
     
	cout << "ConcreteComponent's normal operation!" << endl;
}
// ConcreteDecoratorA.h
#include "Decorator.h"
#include "Component.h"
#include 
using namespace std;

class ConcreteDecoratorA : public Decorator
{
     

public:
	ConcreteDecoratorA(Component* pcmp);
	virtual ~ConcreteDecoratorA();
	void addBehavior();
	virtual void operation();
};

ConcreteDecoratorA::ConcreteDecoratorA(Component* pcmp)
:Decorator(pcmp)
{
     

}

ConcreteDecoratorA::~ConcreteDecoratorA(){
     

}

void ConcreteDecoratorA::addBehavior(){
     
	cout << "addBehavior AAAA" << endl;
}

void ConcreteDecoratorA::operation(){
     
	Decorator::operation();
	addBehavior();
}
// client
#include 
#include "ConcreteComponent.h"
#include "ConcreteDecoratorA.h"
#include "ConcreteDecoratorB.h"
#include "Component.h"
using namespace std;

int main(int argc, char *argv[])
{
     
	ConcreteComponent * pRealProd = new ConcreteComponent();
	Component * pA = new ConcreteDecoratorA(pRealProd);
	pA->operation();
	Component * pB = new ConcreteDecoratorB(pA);
	pB->operation();
	
	delete pRealProd;
	delete pA;
	delete pB;
	return 0;
}

你可能感兴趣的:(设计模式学习)