Factory 方法模式不同於簡單原廠模式的地方在於Factory 方法模式把對象的建立過程放到裡子類裡。這樣工廠父物件和產品父物件一樣,可以是抽象類別或者介面,只定義相應的規範或操作,不涉及具體的建立或實現細節。
其類圖如下:
執行個體代碼為:
#pragma onceclass IProduct{public:IProduct(void);virtual ~IProduct(void);};#pragma once#include "iproduct.h"class IPad :public IProduct{public:IPad(void);~IPad(void);};#pragma once#include "iproduct.h"class IPhone :public IProduct{public:IPhone(void);~IPhone(void);};
#pragma once#include"IProduct.h"class IFactory{public:IFactory(void);virtual ~IFactory(void);virtual IProduct* getProduct();};#pragma once#include "ifactory.h"class IPadFactory :public IFactory{public:IPadFactory(void);~IPadFactory(void);virtual IProduct* getProduct();};#pragma once#include "ifactory.h"class IPhoneFactory :public IFactory{public:IPhoneFactory(void);~IPhoneFactory(void);virtual IProduct* getProduct();};
關鍵的實現:
#include "StdAfx.h"#include "IPadFactory.h"#include"IPad.h"IPadFactory::IPadFactory(void){}IPadFactory::~IPadFactory(void){}IProduct* IPadFactory::getProduct(){return new IPad();}#include "StdAfx.h"#include "IPhoneFactory.h"#include"IPhone.h"IPhoneFactory::IPhoneFactory(void){}IPhoneFactory::~IPhoneFactory(void){}IProduct* IPhoneFactory::getProduct(){return new IPhone();}
調用方式:
#include "stdafx.h"#include"IFactory.h"#include"IPadFactory.h"#include"IPhoneFactory.h"#include"IProduct.h"int _tmain(int argc, _TCHAR* argv[]){IFactory *fac = new IPadFactory();IProduct *pro = fac->getProduct();fac = new IPhoneFactory();pro = fac->getProduct();return 0;}
應用情境:
1. .net裡面的資料庫連接對象就是產生資料命令對象的工廠。每種資料庫的connection對象裡(繼承自IDbConnection)都有對自己createCommand(定義在IDbCommand裡)的實現。
2. .net裡面的迭代器,IEnumerable定義了迭代器的介面,即Factory 方法,每一個繼承自IEnumerable的類都要實現GetEnumerator。可以參看ArrayList,String的GetEnumerator方法。他們都繼承自IEnumerable。
參考資料:
1.Dot Net設計模式—Factory 方法模式 http://fineboy.cnblogs.com/archive/2005/08/04/207459.html
2.Factory 方法模式
http://www.cnblogs.com/cbf4life/archive/2009/12/20/1628494.html
LCL_data原創於CSDN.Net【http://blog.csdn.net/lcl_data/article/details/8712834】