简单工厂模式

2014-11-23 20:27:32 · 作者: · 浏览: 6
简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定哪一个产品类的实例。 工厂类是简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类可以被外界直接调用,创建所需的产品对象。 优点: 外界可以从直接创建具体产品对象的尴尬局面摆脱出来,仅仅需要负责“消费”对象就可以了。而不必管这些对象究竟如何创建及如何组织的.明确了各自的职责和权利,有利于整个软件体系结构的优化。 缺点: 由于工厂类集中了所有实例的创建逻辑,违反了高内聚责任分配原则,将全部创建逻辑集中到了一个工厂类中;它所能创建的类只能是事先考虑到的,如果需要添加新的类,则就需要改变工厂类了。 当系统中的具体产品类不断增多时候,可能会出现要求工厂类根据不同条件创建不同实例的需求.这种对条件的判断和对具体产品类型的判断交错在一起,很难避免模块功能的蔓延,对系统的维护和扩展非常不利; 这些缺点在工厂方法模式中得到了一定的克服。 \
代码:< http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vc3Ryb25nPgo8c3Ryb25nPkZhY3RvcnkuaDwvc3Ryb25nPgoKPHByZSBjbGFzcz0="brush:java;">#include "stdafx.h" class Method { private: int _Num1; int _Num2; public: Method( int number1 = 0, int number2 = 0) :_Num1( number1), _Num2( number2) {} virtual ~Method() {} int GetNum1(){ return _Num1; } int GetNum2(){ return _Num2; } void SetNum1( int number1){ _Num1 = number1; } void SetNum2( int number2){ _Num2 = number2; } virtual int Operator() = 0; }; class ConcreteMethod1 :public Method { public: ConcreteMethod1( int number1 = 0, int number2 = 0) : Method( number1, number2) {} virtual int Operator() { return GetNum1() + GetNum2(); } }; class ConcreteMethod2 :public Method { public: ConcreteMethod2( int number1 = 0, int number2 = 0) : Method( number1, number2) {} virtual int Operator() { return GetNum1() - GetNum2(); } }; class Factory { public: static Method* Create( int style) { Method *me = NULL; switch ( style) { case 1: me = new ConcreteMethod1(); break; case 2: me = new ConcreteMethod2(); break; default: break; } return me; } }; FactoryMethod.cpp
// FactoryMethod.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Factory.h"
#include 
   
    
using namespace std;

int _tmain (int argc , _TCHAR * argv [])
{
        Method * me= NULL;
        Factory fc;
       me = fc.Create(1);
       me->SetNum1(1);
       me->SetNum2(2);
       cout << "result:" << me->Operator() << endl;
       getchar();
        return 0;
}