意图
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
适用性
• 当一个类不知道它所必须创建的对象的类的时候。
• 当一个类希望由它的子类来指定它所创建的对象的时候。
• 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
结构
参与者:
• Product(抽象产品)
— 定义工厂方法所创建的对象的接口。
• ConcreteProduct(具体产品)
— 实现Product接口。
• Creator(抽象工厂类)
— 声明工厂方法,该方法返回一个 Product类型的对象。 Creator也可以定义一个工厂方 法的缺省实现,它返回一个缺省的 ConcreteProduct对象。
— 可以调用工厂方法以创建一个 Product对象。
• ConcreteCreator(具体工厂类)
— 重定义工厂方法以返回一个 ConcreteProduct实例。
优点:
首先,良好的封装性,代码结构清晰。一个对象创建是有条件约束的,如一个调用者需要一个具体的产品对象,只要知道这个产品的类名(或约束字符串)就可以了,不用知道创建对象的艰辛过程,降低模块间的耦合。
UML例子
IProduct.h
#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);
};
IFactory.h
#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();
};
ConcreteFactory
#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();
}
main.cpp
#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;
}