【设计模式】4.装饰器模式

装饰器模式,就是动态的给一个对象增加一些职责。

UML

code

c++ 复制代码
#include "3.h"


int main()
{
	// 有点类似于压栈的感觉, 显示人名 + 装饰1 + 装饰2 + 装饰3 => 输出 装饰321的人
	Person* person = new Person("syc");

	Tshrit* tshrit = new Tshrit();
	tshrit->decorate(person);

	Shoes* shoes = new Shoes();
	shoes->decorate(tshrit);

	Tie* tie = new Tie();
	tie->decorate(shoes);

	tie->show();
	return 0;
}
c++ 复制代码
#pragma once
#include <string>
#include <iostream>
// 形象类
class ICharacter
{
public:
	virtual void show() = 0;
private:
};

// 人
class Person : public ICharacter
{
public:
	Person(const std::string& name) : name(name) {}
	void show() override
	{
		std::cout << "装扮的" << this->name;
	}
private:
	std::string name;
};

// 装饰类
class Decorator : public ICharacter
{
public:
	void decorate(ICharacter* character)
	{
		this->character = character;
	}
	void show() override
	{
		character->show();
	}

protected:
	ICharacter* character;
};

// Tshrit
class Tshrit : public Decorator
{
public:
	void show() override
	{
		std::cout << "T Shrit";
		Decorator::show();
	}
private:
};

// 鞋子
class Shoes : public Decorator
{
public:
	void show() override
	{
		std::cout << "鞋子";
		Decorator::show();
	}
};

// 领带
class Tie : public Decorator
{
public:
	void show() override
	{
		std::cout << "领带";
		Decorator::show();
	}
};
相关推荐
geovindu1 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
geovindu2 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh7 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊8 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua3338 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx9 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥9 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户6242931966210 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊10 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread11 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式