设计模式(3)-装扮你的类(装饰模式)

时间:2022-05-04
本文章向大家介绍设计模式(3)-装扮你的类(装饰模式),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先看看书上的例子吧!人穿衣服的例子!

类图就不画了,就是简单的类结构。

代码如下:

#include <iostream>

using namespace std;

class person{
private:
	string name;
public:
	person(string name){
		this->name = name;
	}

	void wearTShirts(){
		cout<<"大T恤"<<endl;
	}

	void wearBigTrouser(){
		cout<<"跨裤"<<endl;
	}

	void wearSneakers(){
		cout<<"破球鞋"<<endl;
	}

	void wearSuit(){
		cout<<"西装"<<endl;
	}

	void wearTie(){
		cout<<"领带"<<endl;
	}

	void wearLeatherShoes(){
		cout<<"皮鞋"<<endl;
	}

	void show(){
		cout<<"装扮的"<<name.c_str()<<endl;
	}
};

int main(int argc, char* argv[])
{
	person* p = new person("小张");
	cout<<"第一种装扮"<<endl;
	p->wearLeatherShoes();
	p->wearSuit();
	p->wearBigTrouser();
	p->show();
	cout<<"第二种装扮"<<endl;
	p->wearLeatherShoes();
	p->wearTShirts();
	p->wearSneakers();
	p->show();
	return 0;
}

如果要新添加一种装扮,那么就需要修改person类的结构,这样就违反了开闭原则

那就先做抽象好了,把变化的抽象出来,于是类图结构如下

 对应这个实现上面的程序,好像是方便了一些,但是如果继续增加需求呢?就会出现很多的子类。

从而引出装饰模式

装饰模式是动态的给对象增加一些属性和职责

类结构如下

Componment是定义的一个对象接口,可以给这些对象动态的添加职责

ConcertComponent是要被装饰的对象,即原始对象

Dectorator是装饰抽象类

ConcertDectoratorA和ConcertDectoratorB是具体的装饰对象。

看看原来的类图修改如下

这样,就可以实现对人对象的动态装载,不过,这个例子举得感觉不是很好,没有列出装饰模式的精髓。