首页 > 代码库 > 简单工厂模式
简单工厂模式
简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定哪一个产品类的实例。
工厂类是简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类可以被外界直接调用,创建所需的产品对象。
优点:
外界可以从直接创建具体产品对象的尴尬局面摆脱出来,仅仅需要负责“消费”对象就可以了。而不必管这些对象究竟如何创建及如何组织的.明确了各自的职责和权利,有利于整个软件体系结构的优化。
缺点:
由于工厂类集中了所有实例的创建逻辑,违反了高内聚责任分配原则,将全部创建逻辑集中到了一个工厂类中;它所能创建的类只能是事先考虑到的,如果需要添加新的类,则就需要改变工厂类了。
当系统中的具体产品类不断增多时候,可能会出现要求工厂类根据不同条件创建不同实例的需求.这种对条件的判断和对具体产品类型的判断交错在一起,很难避免模块功能的蔓延,对系统的维护和扩展非常不利;
这些缺点在工厂方法模式中得到了一定的克服。
代码:
Factory.h
#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 <iostream> 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。