大话设计模式装饰模式c++实现

装饰模式

其他二十三种设计模式

#include<iostream>

using namespace std;

//装饰模式
//人类
class Person {
    
    
public:
	Person(){
    
    }           //删除会无法引用子类(TShirts、BigTrouser...)的默认构造函数
	
	Person(string _name) {
    
    
		this->name = _name;
	}
	virtual void Show() {
    
    
		cout << "装扮的" << name << endl;
	}

private:
	string name;
};

//抽象服饰类
class Finery :public Person {
    
    
public:
	void Decorate(Person* _component) {
    
    
		this->component = _component;
	}
	virtual void Show(){
    
    
		if (component!=NULL)
		{
    
    
			component->Show();
		}
	}
protected:
	Person* component;
};

//具体服饰类
class TShirts :public Finery {
    
    
public:
	virtual void Show(){
    
    
		cout << "大T恤 ";
		Finery::Show();
	}
};
class BigTrouser :public Finery {
    
    
public:
	virtual void Show() {
    
    
		cout << "垮裤 ";
		Finery::Show();
	}
};
class Sneakers :public Finery {
    
    
public:
	virtual void Show(){
    
    
		cout << "破球鞋 ";
		Finery::Show();
	}
};
class  Suit:public Finery {
    
    
public:
	virtual void Show(){
    
    
		cout << "西装 ";
		Finery::Show();
	}
};
class Tie :public Finery {
    
    
public:
	virtual void Show()  {
    
    
		cout << "领带 ";
		Finery::Show();
	}
};
class LeatherShoes :public Finery {
    
    
public:
	virtual void Show() {
    
    
		cout << "皮鞋 ";
		Finery::Show();
	}
};

void test1() {
    
    
	Person* xc = new Person("小菜");

	cout << "第一种装扮: \n";
	Sneakers* pqx = new Sneakers();
	BigTrouser* kk = new BigTrouser();
	TShirts* dtx = new TShirts();

	pqx->Decorate(xc);
	kk->Decorate(pqx);
	dtx->Decorate(kk);
	dtx->Show();

	delete dtx;
	delete kk;
	delete pqx;
	delete xc;

}
int main() {
    
    
	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114144130
今日推荐