装饰模式又叫包装模式,用继承实现类的功能拓展,可以动态给一个类增加功能。把附加的功能放到单独的类中。 类中的装饰功能从类中搬移去除,可以简化原有类,将核心职责和装饰功能区分来,去除重复的装饰逻辑。 适用:当新加入的东西仅仅为了满足一些只有特定情况下才会执行的特殊行为,而且需要有选择地,有顺序的使用装饰功能包装对象。
顺便体现了一下类的构造析构函数顺序 继承删除父类成员指针这块还没太理解 回头再看下内存泄露方面的东西 具体英雄继承抽象英雄类,抽象武器继承抽象英雄类,具体武器继承抽象武器。创建具体英雄类实例,抽象武器传入英雄指针,具体类实现对应操作。
#include <iostream>
using namespace std;
class AbstractHero {
public:
AbstractHero() {
cout << "AbstractHero构造函数" << endl;
}
virtual void ShowStatus() = 0;
virtual ~AbstractHero() {
cout << "AbstractHero析构" << endl;
}
public:
int mHp;
int mMp;
int mAt;
int mDf;
};
class HeroA :public AbstractHero {
public:
HeroA() {
cout << "HeroA构造函数" << endl;
mHp = 0;
mMp = 0;
mAt = 0;
mDf = 0;
}
virtual void ShowStatus() {
cout << "血量" << mHp << endl;
cout << "魔法" << mMp << endl;
cout << "攻击" << mAt << endl;
cout << "防御" << mDf << endl;
}
virtual ~HeroA() {
cout << "HeroA析构" << endl;
}
};
class AbstractEquipment:public AbstractHero{
public:
AbstractEquipment(AbstractHero* hero) {
this->pHero = hero;
cout << "AbstractEquipment构造函数" << endl;
}
virtual void ShowStatus() {
cout << "血量" << mHp << endl;
cout << "魔法" << mMp << endl;
cout << "攻击" << mAt << endl;
cout << "防御" << mDf << endl;
}
virtual ~AbstractEquipment() {
cout << "AbstractEquipment析构" << endl;
}
public:
AbstractHero *pHero;
};
class AmourEquipment :public AbstractEquipment {
public:
AmourEquipment(AbstractHero* hero): AbstractEquipment(hero){
cout << "AmourEquipment构造函数" << endl;
AddAmour();
}
void AddAmour() {
this->mHp = this->pHero->mHp;
this->mMp = this->pHero->mMp;
this->mAt = this->pHero->mAt;
this->mDf = this->pHero->mDf + 30;
delete pHero;
}
~AmourEquipment() {
cout << "Amour析构" << endl;
}
};
class KnifeEquipment :public AbstractEquipment {
public:
KnifeEquipment(AbstractHero* hero) : AbstractEquipment(hero) {
cout << "KnifeEquipment构造函数" << endl;
AddKnife();
}
void AddKnife() {
this->mHp = this->pHero->mHp;
this->mMp = this->pHero->mMp;
this->mAt = this->pHero->mAt+100;
this->mDf = this->pHero->mDf;
delete pHero;
}
~KnifeEquipment() {
cout << "KnifeEquipment析构" << endl;
}
};
void test01() {
AbstractHero* Hero = new HeroA;
Hero->ShowStatus();
cout << "-------" << endl;
AbstractHero* HeroStatus1 = new AmourEquipment(Hero);
HeroStatus1->ShowStatus();
cout << "-------" << endl;
AbstractHero* HeroStatus2 = new KnifeEquipment(HeroStatus1);
HeroStatus2->ShowStatus();
delete HeroStatus2;
}
int main() {
test01();
system("pause");
return 0;
}
|