作用:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
UML结构图:
抽象基类:
1)Product:创建出来的对象的抽象基类.
2)Factory创建对象的工厂方法的抽象基类.
接口函数:
1)Creator::FactoryMethod:纯虚函数,由派生类实现,创建出对应的Product.
解析:
在这个模式中,有两个抽象基类,一个是Product为创建出来的对象的抽象基类,一个是Factory是工厂的抽象基类,在互相协作的时候都是由相应的Factory派生类来生成Product的派生类,也就是说如果要新增一种Product那么也要对应的新增一个Factory,创建的过程委托给了这个Factory.也就是说一个Factory和一个Product是一一对应的关系.
备注:
设计模式的演示图上把Factory类命名为Creator,下面的实现沿用了这个命名.
演示实现:
1)Factory.h
/**//********************************************************************
created: 2006/06/30
filename: Factory.h
author: 李创
http://www.cppblog.com/converse/
purpose: Factory模式的演示代码
*********************************************************************/
#ifndef FACTORY_H
#define FACTORY_H
class Product
{
public:
Product(){}
virtual ~Product(){}
};
class ConcreateProduct
: public Product
{
public:
ConcreateProduct();
virtual ~ConcreateProduct();
};
class Creator
{
public:
Creator(){}
virtual ~Creator(){}
void AnOperation();
protected:
virtual Product* FactoryMethod() = 0;
};
class ConcreateCreator
: public Creator
{
public:
ConcreateCreator();
virtual ~ConcreateCreator();
protected:
virtual Product* FactoryMethod();
};
#endif
2)Factory.cpp
/**//********************************************************************
created: 2006/06/30
filename: Factory.cpp
author: 李创
http://www.cppblog.com/converse/
purpose: Factory模式的演示代码
*********************************************************************/
#include "Factory.h"
#include <iostream>
using namespace std;
ConcreateProduct::ConcreateProduct()
{
std::cout << "construction of ConcreateProduct\n";
}
ConcreateProduct::~ConcreateProduct()
{
std::cout << "destruction of ConcreateProduct\n";
}
void Creator::AnOperation()
{
Product* p = FactoryMethod();
std::cout << "an operation of product\n";
}
ConcreateCreator::ConcreateCreator()
{
std::cout << "construction of ConcreateCreator\n";
}
ConcreateCreator::~ConcreateCreator()
{
std::cout << "destruction of ConcreateCreator\n";
}
Product* ConcreateCreator::FactoryMethod()
{
return new ConcreateProduct();
}
3)Main.cpp(测试代码)
/**//********************************************************************
created: 2006/06/30
filename: Main.cpp
author: 李创
http://www.cppblog.com/converse/
purpose: 测试Factory模式的代码
*********************************************************************/
#include "Factory.h"
#include <stdlib.h>
int main(int argc,char* argv[])
{
Creator *p = new ConcreateCreator();
p->AnOperation();
delete p;
system("pause");
return 0;
}