C ++ Decorator

C ++ Decorator

#include <iostream>
using namespace std;
//装饰模式又叫包装模式,通过一种对客户端透明的方式来拓展对象功能,是继承关系的一种替代。
//装饰模式就是要把附加的功能分别放在独立的类中,并让这个类包含要装饰的对象
class Hero //英雄类
{
public:
	virtual void ShowProperty() = 0;
public:
	int HP;//血量
	int AT;//攻击
	int DE;//防御
	int MG;//魔法
};
class Thor :public Hero //英雄雷神
{
public:
	Thor() {
		this->HP = 1000;
		this->AT = 180;
		this->DE = 500;
		this->MG = 800;
	}
	void ShowProperty() {
		cout << "血量:" << this->HP << endl;
		cout << "攻击:" << this->AT << endl;
		cout << "防御:" << this->DE << endl;
		cout << "魔法:" << this->MG << endl;
	}
};
class ChangeHero :public Hero {
public:
	ChangeHero(Hero*my){
		this->hero = my;
	}
	virtual void ShowProperty() {};
public:
	Hero*hero;
};
class Armour :public ChangeHero
{
public:
	Armour(Hero*heros):ChangeHero(heros){
		this->HP = this->hero->HP + 200;
		this->AT = this->hero->AT;
		this->DE = this->hero->DE + 500;
		this->MG = this->hero->MG;
		delete this->hero;
	}
	void ShowProperty() {
		cout << "血量:" << HP << endl;
		cout << "攻击:" << AT << endl;
		cout << "防御:" << DE << endl;
		cout << "魔法:" << MG << endl;
	}
};
void test() {
	Hero*my = new Thor;
	my->ShowProperty();
	my = new Armour(my);
	my->ShowProperty();
	delete my;
}
void main() {
	test();
}

Renderings:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44567289/article/details/92760360