工厂方法模式不同于简单工厂模式的地方在于工厂方法模式把对象的创建过程放到里子类里。这样工厂父对象和产品父对象一样,可以是抽象类或者接口,只定义相应的规范或操作,不涉及具体的创建或实现细节。
其类图如下:
实例代码为:
#pragma once
class 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定义了迭代器的接口,即工厂方法,每一个继承自IEnumerable的类都要实现GetEnumerator。可以参看ArrayList,String的GetEnumerator方法。他们都继承自IEnumerable。 |