三、裝飾模式

裝飾模式(Decorator),動態的給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更加靈活。


//Decorator.h
#ifndef _DECORATOR_H
#define _DECORATOR_H
#include <string>
/*Component 類定義一個對象接口,可以給這些對象動態的添加指責*/
class Component
{
public:
	Component();
	virtual ~Component();
	virtual void Operation()=0;

};
/*ConcreteComponent是定義了一個具體的對象,也可以給這個對象添加一些職責*/
class ConcreteComponent:public Component
{
public:
	ConcreteComponent();
	virtual ~ConcreteComponent();
	void Operation();
};
/*Decorator,裝飾抽象類,從外類來擴展Component類的功能
但對於Component來說是無需知道Decorator的存在*/
class Decorator:public Component
{
protected:
	Component* _com;
public:
	Decorator(Component* cpt);
	virtual ~Decorator();
	void Operation();

};
/*具體的裝飾對象,起到給Component添加職責的功能*/
class ConcreteDecoratorA:public Decorator
{
public:
	std::string addState;
	ConcreteDecoratorA(Component* cpt);
	~ConcreteDecoratorA();
	void Operation();
};
class ConcreteDecoratorB:public Decorator
{
public:
	ConcreteDecoratorB(Component* cpt);
	~ConcreteDecoratorB();
	void Operation();
	void AddedBehavior();
};
#endif


//Decorator.cpp
#include "Decorator.h"
#include <iostream>
using namespace std;

Component::Component()
{

}
Component::~Component()
{

}
void Component::Operation()
{

}

ConcreteComponent::ConcreteComponent()
{

}
ConcreteComponent::~ConcreteComponent()
{

}
void ConcreteComponent::Operation()
{
	cout<<"ConcreteComponent Operation"<<endl;
}
Decorator::Decorator(Component* cpt)
{
	_com = cpt;
}
Decorator::~Decorator()
{
	if (!_com)
	{
		delete _com;
	}
}

void Decorator::Operation()
{
	_com->Operation();
}
ConcreteDecoratorA::ConcreteDecoratorA(Component* cpt):Decorator(cpt)
{
}
ConcreteDecoratorA::~ConcreteDecoratorA()
{

}
void ConcreteDecoratorA::Operation()
{
	//先執行父類的operation方法,然後在執行本子類特有的功能
	//相當於對於原Component進行了裝飾
	Decorator::Operation();
	addState = "New state";
	cout<<addState<<endl;
}
ConcreteDecoratorB::ConcreteDecoratorB(Component* cpt):Decorator(cpt)
{

}
ConcreteDecoratorB::~ConcreteDecoratorB()
{

}
void ConcreteDecoratorB::Operation()
{
	Decorator::Operation();
	AddedBehavior();
}
void ConcreteDecoratorB::AddedBehavior()
{
	cout<<"Added behavior from ConcreteDecoratorB"<<endl;
}


//main.cpp
#include <iostream>
#include "Decorator.h"

int main()
{
	Component* cpt = new ConcreteComponent();
	ConcreteDecoratorA* da = new ConcreteDecoratorA(cpt);
	ConcreteDecoratorB* db = new ConcreteDecoratorB(da);
	db->Operation();

	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章