设计模式 之 《工厂方法模式》

GOOD:修正了简单工厂模式中不遵守开放-封闭原则。工厂方法模式把选择判断移到了客户端去实现,

如果想添加新功能就不用修改原来的类,直接修改客户端即可。

简单工厂是个什么东东,工厂模式是个什么西西,在这东东西西之间,存在着怎样南南北北的关系。

下面就让我们揭开工厂方法模式的面纱,然后你可以同之前的简单工厂进行比较,看看他们之间的区别,比较一下各自的优缺点

 

#ifndef __FACTORY_METHOD_MODEL__
#define __FACTORY_METHOD_MODEL__

#include <iostream>
using namespace std;

//实例基类 相当于Product
class LeiFeng
{
public:
    virtual void sweep(){ cout<<"雷锋扫地"<<endl; }
};

//学雷锋的大学生,相当于 ConcreteProduct
class Student : public LeiFeng
{
public:
    virtual void sweep(){ cout<<"大学生扫地"<<endl; }
};

//学雷锋的志愿者,相当于 ConcreteProduct
class Volenter : public LeiFeng
{
public:
    virtual void sweep(){ cout<<"志愿者扫地"<<endl; }
};

//工厂基类 Creator
class LeiFengFactory
{
public:
    virtual LeiFeng* createLeiFeng(){ return new LeiFeng(); }
};

//工厂具体类
class StudentFactory : public LeiFengFactory
{
public:
    virtual LeiFeng* createLeiFeng(){ return new Student();}
};

class VolentorFactory : public LeiFengFactory
{
public:
    virtual LeiFeng* createLeiFeng(){ return new Volenter(); }
};


#endif //__FACTORY_METHOD_MODEL__



《客户端代码》 #include
"FactoryMethodModel.h" int _tmain(int argc, _TCHAR* argv[]) { //创建一个学生工厂的实例 调用学生工厂的createLeiFeng()函数 //创建学生的实例 调用学生的行为 LeiFengFactory* sf = new StudentFactory(); LeiFeng* s = sf->createLeiFeng(); s->sweep(); delete s; delete sf; return 0; }

 

posted @ 2013-10-30 00:03  解放1949  阅读(162)  评论(0编辑  收藏  举报