主要用于创建对象。新添加类时,不会影响以前的系统代码。核心思想是用一个工厂来
根据输入的条件产生不同的类,然后根据不同类的 virtual函数得到不同的结果。
GOOD:适用于不同情况创建不同的类时
BUG:客户端必须要知道基类和工厂类,耦合性差 。
- //基类
- class COperation
- {
- public:
- int m_nFirst;
- int m_nSecond;
- virtual double GetResult() = 0;
- };
- //加法
- class AddOperation : public COperation
- {
- public:
- virtual double GetResult()
- {
- return m_nFirst+m_nSecond;
- }
- };
- //减法
- class SubOperation : public COperation
- {
- public:
- virtual double GetResult()
- {
- return m_nFirst-m_nSecond;
- }
- };
- //工厂类
- class CCalculatorFactory
- {
- public:
- static COperation* Create(char cOperator);
- };
- COperation* CCalculatorFactory::Create(char cOperator)
- {
- COperation *oper;
- //在 C#中可以用反射来取消判断时用的 switch,在C++中用什么呢?RTTI??
- switch (cOperator)
- {
- case '+':
- oper=new AddOperation();
- break;
- case '-':
- oper=new SubOperation();
- break;
- default:
- oper=new AddOperation();
- break;
- }
- return oper;
- }
- 客户端
- int main()
- {
- int a,b;
- cin>>a>>b;
- COperation * op=CCalculatorFactory::Create('-');
- op->m_nFirst=a;
- op->m_nSecond=b;
- cout<<op->GetResult()<<endl;
- return 0;
- }
转载于:https://blog.51cto.com/littlemeng/1182943