作用:
定義一個用於建立對象的介面,讓子類決定執行個體化哪一個類。Factory Method 使一個類的執行個體化延遲到其子類。
UML結構圖:
抽象基類:
1)Product:建立出來的對象的抽象基類.
2)Factory建立對象的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;
}