策略模式
- 类图
- 代码
#includeusing namespace std;class Strategy{public: Strategy() {} ~Strategy() {} virtual void Travel() = 0; };class StrategyWalk : public Strategy{public: StrategyWalk() {} ~StrategyWalk() {} void Travel() { cout << "I walk to my company." << endl; }};class StrategyBus : public Strategy{public: StrategyBus() {} ~StrategyBus() {} void Travel() { cout << "I go to work by bus." << endl; }};class User{public: User() {} ~User() {} void GotoWork() { this->methord->Travel(); } void SetStrategy(Strategy *tool) { this->methord = tool; }private: Strategy *methord;};int main(int argc, char *argv[]){ Strategy *tool = new StrategyBus(); User *tom = new User(); tom->SetStrategy(tool); tom->GotoWork(); delete tool; delete tom; return 0;}