简单工厂模式和策略模式

it2024-11-19  10

//策略模式 #include <iostream> using namespace std; /* 策略模式 和简单工厂模式类似,策略是简单工厂模式中的一个对象 包含在一个客户对象中。 */ /* 使用场景:策略是客户对象的一部分,使用这种方法可以 实现更换策略的无关低耦合 */ class Strategy { public: virtual void AlgorithmInterface() = 0; }; class StrategyClass1 : public Strategy { public: void AlgorithmInterface() { cout<<"Class 1"<<endl; } }; class StrategyClass2 : public Strategy { public: void AlgorithmInterface() { cout<<"Class 2"<<endl; } }; class Context { private: Strategy* m_pStrategy; public: Context(char ch) { m_pStrategy = NULL; switch(ch) { case '1': m_pStrategy = new StrategyClass1(); break; case '2': m_pStrategy = new StrategyClass2(); break; } } ~Context() { delete m_pStrategy; } void ContextInterface() { m_pStrategy->AlgorithmInterface(); } }; int main() { Context* p1 = new Context('1'); p1->ContextInterface(); delete p1; Context* p2 = new Context('2'); p2->ContextInterface(); delete p2; return 0; } //简单工厂模式 #include <iostream> using namespace std; /* 简单工厂模式 根据用户输入生成继承于同一个接口的对象 返回值为基类对象指针,用户可以通过这个指针操作接口方法 */ /* 使用场景:面临着功能性的需求变化,并提供功能的接口一致 使用简单工厂模式可以简单的提供扩展,只需要对于工厂的生 成方法进行改写就可以得到不同对象。 */ class Operation { public: double m_dNumberA; double m_dNumberB; public: virtual double GetResult() = 0; }; class OperationAdd : public Operation { public: double GetResult() { return (m_dNumberA + m_dNumberB); } }; class OperationSub : public Operation { public: double GetResult() { return (m_dNumberA - m_dNumberB); } }; class OperationMul : public Operation { public: double GetResult() { return (m_dNumberA * m_dNumberB); } }; class OperationDiv : public Operation { public: double GetResult() { if (m_dNumberB == 0) return -1; return (m_dNumberA / m_dNumberB); } }; //工厂类 class OperationFactory { public: static Operation* CreateOperate(char operate) { Operation* pOperation = NULL; switch (operate) { case '+': pOperation = new OperationAdd(); break; case '-': pOperation = new OperationSub(); break; case '*': pOperation = new OperationMul(); break; case '/': pOperation = new OperationDiv(); break; } return pOperation; } }; int main() { Operation* pOperation = OperationFactory::CreateOperate('+'); pOperation->m_dNumberA = 3; pOperation->m_dNumberB = 4; cout<<pOperation->GetResult()<<endl; delete pOperation; return 0; }

转载于:https://www.cnblogs.com/yanjiu/archive/2012/08/05/2623590.html

相关资源:数据结构—成绩单生成器
最新回复(0)