设计模式——抽象工厂模式_AbstractFactory

#include <iostream>
using namespace std;

class Human {
public:
	virtual void Talk(){ }
	virtual void GetColour() {}
	virtual void GetSex() {}
};

class AbstractYellowHuman {
public:
	virtual void Talk() = 0;
	virtual void GetColour() = 0;
	virtual void GetSex() = 0;
};
class MaleYellowHuman : public AbstractYellowHuman {
public:
	void Talk() { cout << "我是黄种人,说中文。" << endl; }
	void GetColour() { cout << "黄色皮肤" << endl; }
	void GetSex() { cout << "我是男人!" << endl; }
};
class FamaleYellowHuman : public AbstractYellowHuman {
public:
	void Talk() { cout << "我是黄种人,说中文。" << endl; }
	void GetColour() { cout << "黄色皮肤" << endl; }
	void GetSex() { cout << "我是女人!" << endl; }
};


class AbstractBlackHuman {
public:
	virtual void Talk() = 0;
	virtual void GetColour() = 0;
	virtual void GetSex() = 0;
};
class MaleBlackHuman : public AbstractBlackHuman {
public:
	void Talk() { cout << "我是黑人。不说话" << endl; }
	void GetColour() { cout << "黑色皮肤" << endl; }
	void GetSex() { cout << "公的" << endl; }
};
class FamaleBlackHuman : public AbstractBlackHuman {
public:
	void Talk() { cout << "我是黑人。不说话。" << endl; }
	void GetColour() { cout << "黑色皮肤" << endl; }
	void GetSex() { cout << "母的" << endl; }
};


class HumanFactory {
public:
	virtual AbstractYellowHuman* CreateYellowHuman() = 0;
	virtual AbstractBlackHuman*  CreateBlackHuman() = 0;
};


class MaleFactory : public HumanFactory {
public:
	AbstractYellowHuman* CreateYellowHuman() { return new MaleYellowHuman(); }
	AbstractBlackHuman* CreateBlackHuman() { return new MaleBlackHuman(); }
};

class FamaleFactory : public HumanFactory {
public:
	AbstractYellowHuman* CreateYellowHuman() { return new FamaleYellowHuman(); }
	AbstractBlackHuman*  CreateBlackHuman() { return new FamaleBlackHuman(); }
};
#include "AbstractFactory.h"

int main()
{
	HumanFactory* pFactory = NULL;
	pFactory = new MaleFactory();
	MaleYellowHuman* pMale_Yellow = (MaleYellowHuman*)pFactory->CreateYellowHuman();
	pMale_Yellow->Talk();
	pMale_Yellow->GetColour();
	pMale_Yellow->GetSex();
	cout << "~~~~~~~~~~~~~~~~~~~~~" << endl;
	pFactory = new FamaleFactory();
	FamaleBlackHuman* pFamale_Black = (FamaleBlackHuman*)pFactory->CreateBlackHuman();
	pFamale_Black->Talk();
	pFamale_Black->GetColour();
	pFamale_Black->GetSex();
	return 0;
}


你可能感兴趣的:(设计模式——抽象工厂模式_AbstractFactory)