Java设计模式之策略模式实现教程

1. 流程图

了解策略模式概念 创建接口 创建实现接口的具体策略类 创建上下文类 在上下文类中实现策略的使用 客户端调用

2. 步骤及代码示例

步骤一:了解策略模式概念

策略模式是一种行为设计模式,通过定义一系列算法,将每个算法封装起来,并使它们可以互相替换。这样,客户端在需要使用策略的时候,可以选择不同的策略来达到不同的效果。

步骤二:创建接口
// 策略接口
public interface Strategy {
    void doOperation(int num1, int num2);
}
  • 1.
  • 2.
  • 3.
  • 4.
步骤三:创建实现接口的具体策略类
// 具体策略类A
public class ConcreteStrategyA implements Strategy {
    @Override
    public void doOperation(int num1, int num2) {
        System.out.println("策略A的计算结果:" + (num1 + num2));
    }
}

// 具体策略类B
public class ConcreteStrategyB implements Strategy {
    @Override
    public void doOperation(int num1, int num2) {
        System.out.println("策略B的计算结果:" + (num1 - num2));
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
步骤四:创建上下文类
// 上下文类
public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void executeStrategy(int num1, int num2) {
        strategy.doOperation(num1, num2);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
步骤五:在上下文类中实现策略的使用
// 客户端调用
public class Main {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStrategyA());
        context.executeStrategy(10, 5);  // 输出:策略A的计算结果:15

        context = new Context(new ConcreteStrategyB());
        context.executeStrategy(10, 5);  // 输出:策略B的计算结果:5
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

结尾

通过以上教程,你应该已经掌握了如何在Java中实现策略模式。策略模式可以帮助你实现更灵活和可扩展的代码结构,让你的程序更易于维护和扩展。希望你能够在实际项目中灵活运用策略模式,提高代码的质量和可读性。如果有任何疑问,欢迎随时向我提问。加油!