标签:style blog color io 使用 ar div sp on
简单工厂模式:用一个类负责创建实例的任务,通常是此类中的一个static函数具体负责,此函数中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类。这些实例化的类都派生自同一个父类。使用简单工厂模式,在新增分支时,要新增一个功能子类同时在工厂类中增加逻辑判断分支。
//简单工厂模式 //父类 class Operation { public: Operation() {} virtual ~Operation() {}; void setA( double a ) { m_a = a; } void setB( double b ) { m_b = b; } virtual double getResult() = 0; protected: double m_a; double m_b; }; //加法子类 class Add : public Operation { public: Add() {} virtual ~Add() {} virtual double getResult() { return m_a + m_b; } }; //乘法子类 class Mul : public Operation { public: Mul() {} virtual ~Mul() {} virtual double getResult() { return m_a * m_b; } }; //工厂类 class OperationFactory { public: OperationFactory() {} ~OperationFactory() {} static Operation* createOperation( char ch ) { Operation* ope = NULL; switch ( ch ) { case ‘+‘ : ope = new Add(); break; case ‘*‘ : ope = new Mul(); break; } return ope; } }; int main() { Operation *ope = OperationFactory::createOperation( ‘*‘ ); ope->setA( 3 ); ope->setB( 2 ); double re = ope->getResult(); return 0; }
标签:style blog color io 使用 ar div sp on
原文地址:http://www.cnblogs.com/thinknothing/p/3986261.html