头文件:

#pragma once
#include <iostream>
#include<string>
using namespace std;

class IHuman
{
public:
IHuman(void)
{
}
virtual ~IHuman(void)
{
}
virtual void Laugh() = 0;
virtual void Cry() = 0;
virtual void Talk() = 0;
};



class CYellowHuman :
public IHuman
{
public:
CYellowHuman(void);
~CYellowHuman(void);
void Laugh();
void Cry();
void Talk();
};

class CWhiteHuman :
public IHuman
{
public:
CWhiteHuman(void);
~CWhiteHuman(void);
void Laugh();
void Cry();
void Talk();
};
class CBlackHuman :
public IHuman
{
public:
CBlackHuman(void);
~CBlackHuman(void);
void Laugh();
void Cry();
void Talk();
};

//简单工厂实现
class CSimpleHumanFactory
{
public:
CSimpleHumanFactory(void);
virtual ~CSimpleHumanFactory(void);
virtual IHuman * CreateHuman(string classType);
};

源文件:

#include "cfactorymode.h"


CYellowHuman::CYellowHuman(void)
{
}
CYellowHuman::~CYellowHuman(void)
{
}
void CYellowHuman::Cry()
{
cout << "黄色人种会哭" << endl;
}
void CYellowHuman::Laugh()
{
cout << "黄色人种会大笑,幸福呀!" << endl;
}
void CYellowHuman::Talk()
{
cout << "黄色人种会说话,一般说的都是双字节" << endl;
}

CWhiteHuman::CWhiteHuman(void)
{
}
CWhiteHuman::~CWhiteHuman(void)
{
}
void CWhiteHuman::Cry()
{
cout << "白色人种会哭" << endl;
}
void CWhiteHuman::Laugh()
{
cout << "白色人种会大笑,侵略的笑声" << endl;
}
void CWhiteHuman::Talk()
{
cout << "白色人种会说话,一般都是单字节" << endl;
}

CBlackHuman::CBlackHuman(void)
{
}
CBlackHuman::~CBlackHuman(void)
{
}
void CBlackHuman::Cry()
{
cout << "黑人会哭" << endl;
}
void CBlackHuman::Laugh()
{
cout << "黑人会笑" << endl;
}
void CBlackHuman::Talk()
{
cout << "黑人可以说话,一般人听不懂" << endl;
}


CSimpleHumanFactory::CSimpleHumanFactory(void)
{
}


CSimpleHumanFactory::~CSimpleHumanFactory(void)
{
}


IHuman * CSimpleHumanFactory::CreateHuman( string classType )
{
if (classType.compare("CYellowHuman") == 0)
{
return new CYellowHuman();
}
else if(classType.compare("CWhiteHuman") == 0)
{
return new CWhiteHuman();
}
else if(classType.compare("CBlackHuman") == 0)
{
return new CBlackHuman();
}
}


void FactoryTest()
{
CSimpleHumanFactory *pSimpleHumanFactory = new CSimpleHumanFactory();
cout << "----------第一批人是这样的:黄种人" << endl;
IHuman *pYellowHuman = pSimpleHumanFactory->CreateHuman("CYellowHuman");
pYellowHuman->Cry();
pYellowHuman->Laugh();
pYellowHuman->Talk();
delete pYellowHuman;
cout << "----------第二批人是这样的:白种人" << endl;
IHuman *pWhiteHuman = pSimpleHumanFactory->CreateHuman("CWhiteHuman");
pWhiteHuman->Cry();
pWhiteHuman->Laugh();
pWhiteHuman->Talk();
delete pWhiteHuman;
cout << "----------第三批人是这样的:黑种人" << endl;
IHuman *pBlackHuman = pSimpleHumanFactory->CreateHuman("CBlackHuman");
pBlackHuman->Cry();
pBlackHuman->Laugh();
pBlackHuman->Talk();
delete pBlackHuman;
cout << "----------第四批人是这样的:生产黄种人的工厂,采用了模板的方式。" << endl;
CStandardHumanFactory<CYellowHuman> standardHumanFactory;
pYellowHuman = standardHumanFactory.CreateHuman();
pYellowHuman->Cry();
pYellowHuman->Laugh();
pYellowHuman->Talk();
delete pYellowHuman;

}