工厂方法模式(Factory Method)是另一种生产对象的方式,它把对象的创建封装在一个方法中,子类可以改变工厂方法的生产行为生产不同的对象。工厂方法所属的类不一定是工厂类(抽象工厂或者生成器),它可能是一个普通类、一个框架类,或者是一个自由函数。
GOOD:修正了简单工厂模式中不遵守开放-封闭原则。工厂方法模式把选择判断移到了客户端去实现,如果想添加新功能就不用修改原来的类,直接修改客户端即可。
C++实现:
#include <iostream>
#include <string>
using namespace std;
class LeiFeng
{
public:
virtual void Sweep() { cout << "雷锋扫地" << endl; }
};
class Student : public LeiFeng
{
public:
virtual void Sweep() { cout << "大学生扫地" << endl; }
};
class Volunteer : public LeiFeng
{
public:
virtual void Sweep() { cout << "志愿者扫地" << endl; }
};
class LeiFengFactory
{
public:
virtual LeiFeng* CreateLeiFeng() { return new LeiFeng(); }
};
class StudentFactory : public LeiFengFactory
{
public:
virtual LeiFeng* CreateLeiFeng() { return new Student(); }
};
class VolunteerFactory : public LeiFengFactory
{
public:
virtual LeiFeng* CreateLeiFeng() { return new Volunteer(); }
};
int main()
{
LeiFengFactory* sf = new LeiFengFactory();
LeiFeng* s = sf->CreateLeiFeng();
s->Sweep();
delete sf;
return 0;
}
参考:大话设计模式实现(C++版)