1. 程式人生 > >裝飾模式C++實現

裝飾模式C++實現






























#include <iostream>
#include <string>
class Person
{
public:
	Person() = default;
	virtual void showDecorator() {
		return;
	}
};
class Man : public Person
{
public:
	Man() = default;
	Man(std::string str) : Name(str){}
	void showDecorator() {
		std::cout << Name << "裝飾: ";
	}
private:
	std::string Name;
};
class Women : public Person
{
public:
	Women() = default;
	Women(std::string str) : Name(str){}
	void showDecorator() {
		std::cout << Name << "裝飾: ";
	}
protected:
private:
	std::string Name;
};
class Decorator : public Person
{
public:
	Decorator() = default;
	Decorator(Person* p) :persond(p){}
	virtual void showDecorator() {
		persond->showDecorator();
	}
private: 
	Person* persond;
};
class DecoratorA : public Decorator
{
public:
	DecoratorA() = default;
	DecoratorA(Person* p) :Decorator(p){}
	void showDecorator(){
		Decorator::showDecorator();
		addDecrator();
	}
protected:
private:
	void addDecrator() {
		std::cout << "頭髮 ";
	}
};
class DecoratorB : public Decorator
{
public:
	DecoratorB() = default;
	DecoratorB(Person *p) : Decorator(p){}
	void showDecorator(){
		Decorator::showDecorator();
		addDecorator();
	}
protected:
private:
	void addDecorator(){
		std::cout << "服裝 ";
	}
};
void main() {
	Person *ps = new Man("張三");
	Person *hair = new DecoratorA(ps);
	Person *clothes = new DecoratorB(hair);
	clothes->showDecorator();
	delete clothes;
	delete hair;
	delete ps;
	return;
}