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

来源:互联网 发布:移动网络电视不能看 编辑:程序博客网 时间:2024/05/16 20:30
// 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;}

0 1
原创粉丝点击