【设计模式】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();
	}
};
相关推荐
静水流深_沧海一粟12 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder12 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室19 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈5 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||5 天前
安装依赖三方exe/msi的软件设计模式
设计模式