核心思想:用一个工厂类根据不同的输入条件new出不同的派生类指针,然后由多态调用不同派生类中virtual函数,得到不同的结果
所有的判断处理在工厂类中完成,通过CreateFactory函数,根据不同的类型,new出派生类指针,返回基类指针。
代码如下:
1 class CFactory 2 { 3 public: 4 CFactory(void); 5 ~CFactory(void); 6 7 public: 8 static IOperator* CreateFactory(char cStr); 9 }; 10 11 IOperator* CFactory::CreateFactory(char cStr) 12 { 13 IOperator *pStr = NULL; 14 switch(cStr) 15 { 16 case '+': 17 { 18 pStr = new CAddOperator(); 19 } 20 break; 21 case '-': 22 { 23 pStr = new CSubtract(); 24 } 25 break; 26 default: 27 break; 28 } 29 30 return pStr; 31 } 32 33 class IOperator 34 { 35 public: 36 IOperator(void); 37 virtual ~IOperator(void); 38 39 public: 40 virtual int Result() = 0; 41 42 public: 43 int m_nA; 44 int m_nB; 45 }; 46 47 class CAddOperator : public IOperator 48 { 49 public: 50 CAddOperator(void); 51 ~CAddOperator(void); 52 53 public: 54 virtual int Result(); 55 }; 56 57 class CSubtract : public IOperator 58 { 59 public: 60 CSubtract(void); 61 ~CSubtract(void); 62 63 public: 64 virtual int Result(); 65 }; 66 外部调用:
67 IOperator *pTemp = CFactory::CreateFactory('+'); 68 if (NULL != pTemp) 69 { 70 pTemp->m_nA = 4; 71 pTemp->m_nB = 3; 72 73 int i = pTemp->Result(); 74 }