您的位置:首页 > 编程语言 > C语言/C++

C++ 设计模式之二(Factory Method模式)

2007-08-30 11:36 288 查看
工厂方法(Factory Method)模式的核心是一个抽象工厂类,各种具体工厂类通过抽象工厂类将工厂方法继承下来。这样,使得客户只关心抽象产品和抽象工厂,完全不用理会返回的是哪一种具体产品,也不用关心它是如何被具体工厂创建的。



UML 结构图

  下面的例子演示了钢笔厂和铅笔厂的工作过程。

Product.h 代码如下:

/*
作者: zhang_gl
blog:http://blog.csdn.net/zgl_dm/
描述:Fatory Method Pattern
*/


#ifndef _PRODUCT_H_


#define _PRODUCT_H_


#include "Factory.h"




class Product




...{


public:


virtual void Output()=0;


};




class Pen:public Product




...{


public:


void Output();


};




class Pencil:public Product




...{


public:


void Output();


};


#endif

Factory.h 代码如下:


#ifndef _FACTORY_H_


#define _FACTORY_H_


#include "Product.h"


#include <iostream>


#include <string>




using namespace std;




class Product;


class Pen;


class Pencil;




class Factory




...{


public:


virtual Product* Produce()=0;


};




class PenFactory:public Factory




...{


public:


Product *Produce();


};




class PencilFactory:public Factory




...{


public:


Product *Produce();


};




#endif

Product.cpp 代码如下:


#include "Product.h"




void Pen::Output()




...{


cout<<"The pen is produced ";


}


void Pencil::Output()




...{


cout<<"The Pencil is produced ";


}

Factory.cpp 代码如下:


#include "Factory.h"




Product * PenFactory::Produce()




...{


return new Pen();


}




Product * PencilFactory::Produce()




...{


return new Pencil();


}

Main 函数如下:


#include "Factory.h"


#include "Product.h"




void main()




...{


Factory *factory=new PenFactory();


Product *product=factory->Produce();


product->Output();




factory=new PencilFactory();


product=factory->Produce();


product->Output();


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: