栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++设计模式 装饰器模式

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++设计模式 装饰器模式

提出的动机来源于对继承的乱用导致的派生类急速增加的问题。
主要是要分清楚积累的派生分别是往“主体”走的or往“拓展”走的
装饰器模式特征一般比较明显,父类在被派生类继承的同时也被包含了
(用侯捷老师的话是委托delegation,因为这里用的是指针)。

//头文件
#pragma once
#include 
using namespace std;
//基类
template
class component {
public:
	virtual void _charactor() {}
	virtual void attch() {}
	virtual void describe() {}
};
//基类的“主体”派生1
template
class component1 :public component {
public:
	virtual void _charactor() {
		cout << "一类人员";
	}
};
//基类的“主体”派生2
template
class component2 : public component {
public:
	virtual void _charactor() {
		cout << "二类人员" ;
	}
};
//装饰器(这里作为中间类,因为觉得每个装饰器都有component* Component不是很规范)
template
class decorator :public component {
public:
	virtual void _charactor() {
		Component->_charactor();
	}
	virtual void describe() {
		attach();
		cout << endl;
	}
protected:
	decorator(component* com) :Component(com) {}
	component* Component;
	virtual void attach() {
		cout << "存放附加属性的虚函数" << endl;
	}
};
//具体装饰器1
template
class dec_1component :public decorator {
protected:
	virtual void attach() {
		cout << " 又被装饰器1装饰了 ";
	}
public:
	dec_1component(component* com) :decorator(com) {}//这里为什么变量是这个?好像是调用 decortor的构造函数
};
//具体装饰器2
template
class dec_2component :public decorator {
protected:
	virtual void attach() {
		cout << " 又被装饰器2装饰了 ";
	}
public:
	dec_2component(component* com) :decorator(com) {}
};

调用接口:

	//测试装饰器模式
	cout << "测试装饰器模式" << endl;
	component1* Lihua = new component1;//一个单纯的一类成员
	dec_1component* Lihua_1 = new dec_1component(Lihua);//一个附加了dec_1的一类成员
	dec_2component* Lihua_2 = new dec_2component(Lihua);//一个附加了dec_2的一类成员
	dec_2component* Lihua_12 = new dec_2component(Lihua_1);//一个附加了dec_1和dec_2的一类成员
	Lihua->describe();
	Lihua_1->describe();
	Lihua_2->describe();
	Lihua_12->describe();
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/722168.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号