设计模式-策略模式

在Java中实现策略模式,可以通过定义一个策略接口和多个具体策略类,然后在上下文类中使用这些策略。以下是一个简单的Java策略模式示例:

策略接口

java 复制代码
// 策略接口
public interface Strategy {
    void algorithmInterface();
}

具体策略类

java 复制代码
// 具体策略A
public class ConcreteStrategyA implements Strategy {
    @Override
    public void algorithmInterface() {
        System.out.println("Algorithm A");
    }
}

// 具体策略B
public class ConcreteStrategyB implements Strategy {
    @Override
    public void algorithmInterface() {
        System.out.println("Algorithm B");
    }
}

上下文类

java 复制代码
// 上下文类
public class Context {
    private Strategy strategy;

    // 设置策略
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    // 执行策略
    public void executeStrategy() {
        strategy.algorithmInterface();
    }
}

客户端代码

java 复制代码
public class StrategyPatternDemo {
    public static void main(String[] args) {
        Context context = new Context();

        // 使用策略A
        context.setStrategy(new ConcreteStrategyA());
        context.executeStrategy();  // 输出: Algorithm A

        // 使用策略B
        context.setStrategy(new ConcreteStrategyB());
        context.executeStrategy();  // 输出: Algorithm B
    }
}

运行结果

复制代码
Algorithm A
Algorithm B

解释

  1. Strategy 接口 :定义了一个算法接口 algorithmInterface
  2. ConcreteStrategyA 和 ConcreteStrategyB :实现了 Strategy 接口,提供了具体的算法实现。
  3. Context 类 :持有一个 Strategy 对象,并通过 setStrategy 方法来设置具体的策略。通过 executeStrategy 方法来执行当前策略的算法。
  4. StrategyPatternDemo:客户端代码,演示了如何使用不同的策略。

通过这种方式,可以在运行时动态地改变对象的行为,而无需修改上下文类的代码。

相关推荐
sg_knight5 小时前
适配器模式(Adapter)
python·设计模式·适配器模式·adapter
郝学胜-神的一滴9 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
九狼11 小时前
Riverpod 2.0 代码生成与依赖注入
flutter·设计模式·github
geovindu13 小时前
python: Visitor Pattern
python·设计模式·访问者模式
五阿哥永琪13 小时前
常见设计模式简介
设计模式
资深web全栈开发1 天前
CQS - 命令查询分离:驯服副作用
设计模式
geovindu1 天前
python: Template Method Pattern
开发语言·python·设计模式·模板方法模式
HY小海2 天前
【Unity游戏创作】常见的设计模式
unity·设计模式·c#·游戏程序
Yongqiang Cheng2 天前
设计模式:C++ 模板方法模式 (Template Method in C++)
设计模式·template method·c++ 模板方法模式
我爱cope2 天前
【从0开始学设计模式-3| 工厂模式】
设计模式