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

code
#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;
}
#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();}
};