现在的位置: 首页 > 综合 > 正文

工厂方法 Factory Method 建立对象的实例交给子类

2019年01月09日 ⁄ 综合 ⁄ 共 1033字 ⁄ 字号 评论关闭
// 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;
}

抱歉!评论已关闭.