【设计模式】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();
	}
};
相关推荐
高晶5 小时前
ARM 嵌入式 Linux 系统启动流程实战指南
设计模式·程序员
高晶5 小时前
BMS 通信开发实战:从 PMBus 协议到数据采集的完整指南
设计模式·程序员
geovindu5 小时前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
电子IT笔记5 小时前
老MES登录改造:弱密码和暴破一起治
设计模式
牧瀬クリスだ7 小时前
单例模式终极指南:从入门到防破坏
单例模式·设计模式
博风11 小时前
9、设计模式应用举例:责任链模式:计算阶乘
设计模式·责任链模式
电子IT笔记13 小时前
人走了,记录不能“空白”: MES×HR 离职人员下拉回显实战
设计模式
博风1 天前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶1 天前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员
geovindu2 天前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式