// example12.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
/*
如果你的應用要動態生成的對象種類繁雜,那還是把他管理起來吧。
讓專門的工廠來實現這個需求吧,調用只需要告訴工程你要什麼,
具體如何生成,讓別人去做。
*/
//抽象定義一個產品,並讓這個產品有表現自己的能力
class product
{
public:
virtual void showMyFunction()=0;
};
//定義一個生產產品的抽象工程,他很厲害,什麼都能生產,反正他不具體生產
class factory
{
public:
virtual product* createProduce(int criterior)=0;
};
//電視機產品
class television : public product
{
public:
void showMyFunction()
{
printf("you can watch me, and relax yourself\n");
};
};
//洗衣機產品
class washmachine : public product
{
public:
void showMyFunction()
{
printf("you can wash your clothes by my help, save your engery\n");
};
};
//具體的工廠你來生產這些東西吧
class concretefactory : public factory
{
public:
product* createProduce(int criterior)
{
product* p = NULL;
if (1 == criterior)
{
p = new television;
}
else if(2 == criterior)
{
p = new washmachine;
}
return p;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
concretefactory fac;
//讓工程來生產吧, 有需求就給工廠吧,
product* TV = fac.createProduce(1);
product* WashMachine = fac.createProduce(2);
//得到產品後你就盡情享受吧,不需要付費的喲。
TV->showMyFunction();
WashMachine->showMyFunction();
delete TV;
delete WashMachine;
getchar();
return 0;
}
工廠方法 Factory Method 建立對象的實例交給子類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.