工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定去实例化那一个类,工厂方法使一个类的实例化延续到其子类。
UML类图:
工厂方法模式基本代码如下:
/********************************************************************
filename: FactoryMethod.h
created: 2012-09-21
author: firehood
purpose: firehood 学设计模式之---工厂方法模式
*********************************************************************/
#pragma once
#include <iostream>
using namespace std;
// 抽象产品
class Product
{
public:
Product(){}
virtual ~Product(){}
};
// 具体产品A
class ConcreteProductA : public Product
{
public:
ConcreteProductA()
{
cout<<"生产产品A"<<endl;
}
virtual ~ConcreteProductA()
{
cout<<"销毁产品A"<<endl;
}
};
// 具体产品B
class ConcreteProductB : public Product
{
public:
ConcreteProductB()
{
cout<<"生产产品B"<<endl;
}
virtual ~ConcreteProductB()
{
cout<<"销毁产品B"<<endl;
}
};
// 抽象工厂
class Creator
{
public:
Creator(){};
virtual ~Creator(){};
Product* CreateProduct()
{
return FactoryMethod();
}
protected:
virtual Product* FactoryMethod() = 0;
};
// 具体工厂A
class ConcreteCreatorA : public Creator
{
public:
ConcreteCreatorA()
{
cout<<"创建工厂A"<<endl;
}
virtual ~ConcreteCreatorA()
{
cout<<"销毁工厂A"<<endl;
}
protected:
virtual Product* FactoryMethod()
{
return new ConcreteProductA();
}
};
// 具体工厂B
class ConcreteCreatorB : public Creator
{
public:
ConcreteCreatorB()
{
cout<<"创建工厂B"<<endl;
}
virtual ~ConcreteCreatorB()
{
cout<<"销毁工厂B"<<endl;
}
protected:
virtual Product* FactoryMethod()
{
return new ConcreteProductB();
}
};
客户端调用代码:
int main(int argc,char* argv[])
{
cout<<"*************************************"<<endl;
cout<<"firehood 学设计模式之---工厂方法模式"<<endl;
cout<<"*************************************"<<endl;
Creator *factoryA = new ConcreteCreatorA();
Product *productA = factoryA->CreateProduct();
Creator *factoryB = new ConcreteCreatorB();
Product *productB = factoryB->CreateProduct();
delete productA;
delete factoryA;
delete productB;
delete factoryB;
system("pause");
return 0;
}
运行结果:
*************************************
firehood 学设计模式之---工厂方法模式
*************************************
创建工厂A
生产产品A
创建工厂B
生产产品B
销毁产品A
销毁工厂A
销毁产品B
销毁工厂B