cpp/c++ 设计模式之策略模式。
策略模式将算法的实现和使用分离,当想要更换新算法时,使用接口保持不变。
4月4日 - fayige.top
以解数学题为例,对同一个题我们可以找到多个不同的解法。
文件名:dp_strategy_pattern.cpp
#include <iostream> namespace pattern { class strategy { public: virtual ~strategy() = default; public: virtual void solve_equation() = 0; }; class method_1: virtual public pattern::strategy { public: void solve_equation() override { std::cout << "用方法1" << std::endl; } }; class method_2: virtual public pattern::strategy { public: void solve_equation() override { std::cout << "用方法2" << std::endl; } }; class solution_context { public: virtual ~solution_context() = default; protected: pattern::strategy & strategy; public: solution_context(pattern::strategy & s__): strategy(s__) { } public: virtual void solve_equation() { strategy.solve_equation(); } }; } // namespace pattern int main() { pattern::method_1 m1; pattern::method_2 m2; pattern::solution_context s1{m1}; pattern::solution_context s2{m2}; std::cout << "解方程:" << std::endl; s1.solve_equation(); std::cout << "解方程:" << std::endl; s2.solve_equation(); }
解方程: 用方法1 解方程: 用方法2
Copyright 2024 fayige.top
Distributed under the Boost Software License, Version 1.0.
(See accompanying
file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)