简单工厂模式应该是所有设计模式中最简单,也最基础的一种模式,以下是一个简单的采用工厂模式写一个加减法的计算器。
1、抽象接口类——依赖倒转原则(高层和底层都要依赖于抽象,针对接口编程)
class IOperation { public: IOperation() : m_nNuml(0), m_nNumr(0) {} virtual ~IOperation() {} virtual void SetNum(int nNuml = 0, int nNumr = 0) { m_nNuml = nNuml; m_nNumr = nNumr; } virtual int CalculateResult() = 0; protected: int m_nNuml, m_nNumr; };
注:m_nNuml, m_nNumr申明为protected,是为了让继承类中能够使用,同时又保持其访问的私有性,这和C#是不一样的地方
2、接口实现对象类——加法、减法类(乘除法就省略了,类似)
class COperation_Add : public IOperation { public: int CalculateResult() { return m_nNuml + m_nNumr; } }; class COperation_Dec : public IOperation { public: int CalculateResult() { return m_nNuml - m_nNumr; } };
<span style="font-size:14px;">class CClassFactory { public: CClassFactory() {} ~CClassFactory() {} IOperation* CreateObject(char cOperation) { IOperation* poCOperation = NULL; switch (cOperation) { case '+': { poCOperation = new COperation_Add(); break; } case '-': { poCOperation = new COperation_Dec(); break; } break; } return poCOperation; } };
void Test() { CClassFactory oCClassFactory; IOperation* poIOperation = NULL; poIOperation = oCClassFactory.CreateObject('+'); if (poIOperation) { poIOperation->SetNum(2, 3); printf("2 + 3 = %d\n", poIOperation->CalculateResult()); delete poIOperation; } }
原文地址:http://blog.csdn.net/gufeng99/article/details/45932177