作用:
定義一個用於創建對象的接口,讓子類決定實例化哪一個類。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;
}