【设计模式】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();
	}
};
相关推荐
Zane19943 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫4 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19944 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19945 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..5 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1506 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)6 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki7 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅667 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa7 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio