今天来学习一下工厂方法模式,先看一下C++代码的实现。

#include <iostream> 
#include <string> 
#include <list>
#include <math.h> 
#include <stdlib.h>
using namespace std;


//工厂方法模式
class LeiFeng
{
public:
	void Sweep()
	{
		cout << "Sweep" << endl;
	}

	void Wash()
	{
		cout << "Wash" << endl;
	}

	void BuyRice()
	{
		cout << "BuyRice" << endl;
	}
};

class Undergraduate : public LeiFeng  //大学生
{
};

class Volunteer : public LeiFeng   //自愿者
{
};


class IFactory  //子类重写父类的虚函数
{
public:
	virtual LeiFeng *CreateLeiFeng() 
	{
		return new LeiFeng();
	}  
};

class UndergraduateFactory : public IFactory
{
public:
	LeiFeng *createLeiFeng()
	{
		return new Undergraduate();
	}

};

class VolunteerFactory : public IFactory
{
public:
	LeiFeng *CreateLeiFeng()
	{
		return new Volunteer();
	}
};


int main()
{
	//工厂方法
	IFactory *factory = new UndergraduateFactory();
	LeiFeng *student = factory->CreateLeiFeng();

	student->BuyRice();
	student->Sweep();
	student->Wash();

        delete factory;

	return 0;
}

代码场景是有大学生和志愿者都要去学雷锋,但是需要判断是大学生还是自愿者。如果用简单工厂模式,则需要在工厂类中进行判断,后面在加入新的需要修改工厂类,这就等于不但对扩展开放了,对修改也开放了,违背了开放-封闭原则。

工厂方法模式有一个身份类(大学生和志愿者类)和一个工厂类,每个身份对应一个工厂类,这样我们通过创建工厂类就实例化了对应的身份类,当有新的身份加进来时,我们只需要增加新类,不需要修改以前的代码。工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码进行。你想要增加功能,本来是修改工厂类的,而现在是修改客户端。

 

 

 

参考资料:大话设计模式