[大话设计模式] 第6章: 装饰模式

装饰模式(Decorator)

  • 装饰模式:动态的给一个对象添加一些额外的职能,把所需功能按顺序串联起来并进行控制。
  • 每个要装饰的功能放在单独的类中,并让这个类包装它所要修饰的对象。当需要执行特殊行为时,客户端就可以根据需要有选择的、有顺序的使用装饰功能包装对象了。
  • 装饰模式有效的把类的核心职能和装饰功能区分开了,并且可以去除相关类中重复的装饰逻辑。

UML类图

  • Component:定义一个对象接口,可以给这些对象动态地添加职责;
  • ConcreteComponent:定义一个具体的Component,继承自Component,重写了Component类的虚函数;
  • Decorator:维持一个指向Component对象的指针,该指针指向需要被装饰的对象;并定义一个与Component接口一致的接口;
  • ConcreteDecorator:向组件添加职责。

装饰模式穿衣服举例

UML类图

#include <iostream>

class Person
{
public:
	virtual ~Person(){}
	virtual void show(){ }
};

// 服饰类(Decorator)
class Finery : public Person
{
public:
	Finery(Person *p): component(p){}
	void show() override {}
protected:
	Person *component;
};

class Tie : public Finery
{
public:
	Tie(Person *p): Finery(p){ }
	void show() override{
		std::cout << "tie " << std::endl;
		component->show();
 	}
};

class Suit : public Finery
{
public:
	Suit(Person *p): Finery(p){ }
	void show() override{
		std::cout << "suit " << std::endl;
		component->show();
 	}
};

class Shoes : public Finery
{
public:
	Shoes(Person *p): Finery(p){ }
	void show() override{
		std::cout << "shoes " << std::endl;
		component->show();
 	}
};

int main()
{
	Person *xc = new Person();
	Tie    *t  = new Tie(xc);
	Shoes  *s  = new Shoes(t);
	s->show();

	delete xc;
	delete t;
	delete s;

	return 0;
}

/* 输出结果
shoes
tie
*/

参考链接

大话设计模式C++源码: https://github.com/yogykwan/design-patterns-cpp

原文地址:https://www.cnblogs.com/moon1992/p/7267946.html