【设计模式】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();
	}
};
相关推荐
进击的小头3 小时前
设计模式组合应用:嵌入式通信协议栈
c语言·设计模式·策略模式
致Great3 小时前
智能体的设计模式探讨
设计模式
BD_Marathon5 小时前
设计模式——单一职责原则
设计模式·单一职责原则
stevenzqzq5 小时前
Slot API 设计模式
设计模式·compose
reddingtons5 小时前
Cascadeur:动态总是“飘”?“物理外挂流” 3分钟直出重力感 2D 立绘
游戏·设计模式·aigc·设计师·游戏策划·游戏美术·cascadeur
Wyy_9527*5 小时前
行为型设计模式——策略模式
设计模式·策略模式
kogorou0105-bit6 小时前
前端设计模式:发布订阅与依赖倒置的解耦之道
前端·设计模式·面试·状态模式
BD_Marathon6 小时前
设计模式——接口隔离原则
java·设计模式·接口隔离原则
小码过河.1 天前
设计模式——适配器模式
设计模式·适配器模式
钝挫力PROGRAMER1 天前
软件工程结构型设计模式
设计模式·软件工程