设计模式之简单工厂
介绍:从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(StaticFactory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。
UML图示:
代码实现:class Operator { private: double m_numberA; double m_numberB; public: virtual double GetResult(); void SetNumberA(double a) { m_numberA = a; } void SetNumberB(double b) { m_numberB = b; } }; class OperatorAdd : public Operator { public: double GetResult() { return m_numberA + m_numberB; } }; class OperatorSub : public Operator { public: double GetResult() { return m_numberA - m_numberB; } }; class OperatorMul : public Operator { public: double GetResult() { return m_numberA * m_numberB; } }; class OperatorDiv : public Operator { public: double GetResult() { if (0 == m_numberB) { printf("除数不能为零!\n"); return 0; } return m_numberA / m_numberB; } }; class SimpleFactory { public: Operator* CreateOperator(char c) { Operator* oper = NULL; switch (c) { case '+': oper = new OperatorAdd(); break; case '-': oper = new OperatorSub(); break; case '*': oper = new OperatorMul(); break; case '/': oper = new OperatorDiv(); break; default: break; } return oper; } }; int main() { SimpleFactory factory; Operator* oper = NULL; oper = factory.CreateOperator('+'); oper->SetNumberA(10.0); oper->SetNumberB(2.0); printf("result:%d\n", oper->GetResult()); return 0; }
不积跬步无以至千里,不积小流无以成江河。