大话设计模式 —— 策略模式

一、模式介绍

       策略模式适合封装算法的不同实现(比如上文 大话设计模式 —— 简单工厂模式 中的数学运算)

       策略模式能够将实现的细节进一步封装,客户端代码无需知道具体算法实体是什么,就可以完成正确的运算

       上文中,客户端(Main.java)实际上是需要了解 Operation 运算父类的,而使用策略模式能够将其屏蔽,进一步解耦

       策略模式,将工厂类变成策略类,根据传入参数不同生产不同策略对象(内置),然后提供公开方法

二、使用策略模式实现计算器

       上文中的 Operation 接口 、AddOperation、SubOperation、DefaultOperation 继续复用

       我们定义一个算法策略

public class ComputeContext {

    private Operation opt;

    public ComputeContext(String operate) {
        switch (operate) {
        case "+":
            opt = new AddOperation();
            break;
        case "-":
            opt = new SubOperation();
            break;
        default:
            opt = new DefaultOperation();
        }
    }

    public int compute(int num1, int num2) {
        return opt.compute(num1, num2);
    }

}

       测试类(Main 不需要知道 Operation 类的存在,相比简单工厂,进一步解耦了)

public class Main {

    public static void main(String[] args) {
        ComputeContext ctx = new ComputeContext("+");
        System.out.println(ctx.compute(1, 2));
        ctx = new ComputeContext("-");
        System.out.println(ctx.compute(1, 2));
    }

}

 

### C++ 中的策略模式 #### 策略模式概述 策略模式是一种行为型设计模式,它定义了一系列算法,并将每个算法封装起来,使它们可以互换。这种模式使得算法可以在不影响客户端的情况下发生变化[^3]。 #### UML 图解 在策略模式中,通常有一个上下文(Context)类用于维持对某个具体策略(Concrete Strategy)实例的引用。而所有的具体策略都实现了相同的接口(Strategies Interface),这允许Context能够调用任何具体的策略而不必关心其内部细节[^4]。 #### 实现步骤 为了实现这一模式,在C++里首先要创建一个表示不同策略的行为接口: ```cpp // 定义策略基类 class IStrategy { public: virtual ~IStrategy() {} virtual void execute() const = 0; }; ``` 接着为各种可能的具体操作提供多个派生自`IStrategy`的不同版本: ```cpp // 具体策略A class ConcreteStrategyA : public IStrategy { public: void execute() const override { std::cout << "Executing strategy A\n"; } }; // 具体策略B class ConcreteStrategyB : public IStrategy { public: void execute() const override { std::cout << "Executing strategy B\n"; } }; ``` 最后构建一个持有并能切换当前所使用的策略的对象——即所谓的“环境”或“上下文”。 ```cpp // 上下文类 class Context { private: IStrategy* _strategy; public: // 构造函数接收一个初始策略 explicit Context(IStrategy& s):_strategy(&s){} // 设置新的策略 void set_strategy(IStrategy& new_strategy){ _strategy=&new_strategy; } // 执行选定的策略 void perform_operation(){ if (_strategy != nullptr) _strategy->execute(); else std::cerr<<"No strategy selected.\n"; } }; ``` 这样就完成了简单的策略模式框架搭建。当需求改变时只需新增加对应的策略类即可满足扩展性的要求[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值