设计模式的理会和实现(C++)之一-Factory模式
副标题#e#
浸染:
界说一个用于建设工具的接口,让子类抉择实例化哪一个类。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
#p#副标题#e#
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;
}