• 设计模式:策略模式


    策略模式(Strategy Pattern)是一种行为型设计模式,它允许在运行时选择算法的行为。在策略模式中,将不同的算法封装成独立的策略类,可以根据需要动态地切换或选择不同的策略,而不需要修改客户端代码。

    策略模式的核心思想是将算法的定义和使用分离开来,使得它们可以独立变化。它由三个主要角色组成:

    1. Context(上下文): 上下文类是策略模式中的环境类,它负责与客户端进行交互。上下文类内部持有一个策略接口的引用,并在需要调用算法时,通过策略接口调用具体的策略类。

    2. Strategy(策略): 策略接口是策略模式的核心,它定义了具体策略类所需实现的方法。不同的策略类实现相同的策略接口,但提供不同的具体算法实现。

    3. Concrete Strategy(具体策略): 具体策略类实现了策略接口,并提供了具体的算法实现。在上下文环境中,根据需要选择使用的具体策略类。

    使用策略模式可以提高代码的可维护性和扩展性,因为不同的算法实现被封装在独立的策略类中,可以独立地进行修改、测试和扩展。它也符合开闭原则,即对扩展开放,对修改关闭。

    总结起来,策略模式通过将算法封装成独立的策略类,可以在运行时动态地选择和切换不同的算法,提高代码的灵活性和可扩展性。


    以下是一个简单的策略模式的代码实现示例:

    首先,定义一个策略接口(Strategy):

    public interface Strategy {
        void execute();
    }
    
    • 1
    • 2
    • 3

    然后,实现具体的策略类:

    public class ConcreteStrategy1 implements Strategy {
        @Override
        public void execute() {
            System.out.println("执行策略1");
        }
    }
    
    public class ConcreteStrategy2 implements Strategy {
        @Override
        public void execute() {
            System.out.println("执行策略2");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    接下来,创建上下文类(Context):

    public class Context {
        private Strategy strategy;
    
        public Context(Strategy strategy) {
            this.strategy = strategy;
        }
    
        public void setStrategy(Strategy strategy) {
            this.strategy = strategy;
        }
    
        public void executeStrategy() {
            strategy.execute();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    最后,可以在客户端中使用策略模式:

    public class Client {
        public static void main(String[] args) {
            Context context = new Context(new ConcreteStrategy1());
            context.executeStrategy(); // 输出:执行策略1
    
            context.setStrategy(new ConcreteStrategy2());
            context.executeStrategy(); // 输出:执行策略2
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在上面的示例中,我们定义了两个具体的策略类(ConcreteStrategy1和ConcreteStrategy2),它们都实现了策略接口(Strategy)。然后,我们通过上下文类(Context)来使用不同的策略,可以通过调用setStrategy()方法来切换策略,并通过executeStrategy()方法来执行具体的策略。

    这样,我们就可以在运行时选择不同的策略,而不需要修改客户端的代码。这就是策略模式的核心思想。

  • 相关阅读:
    OpenGL运行环境的搭建(GLFW+GLAD+OpenGL以及在Vistual Studio中的 配置)
    Github 2024-06-03 开源项目日报 Top9
    Go实战学习笔记-1.Go安装、介绍及Go Playground介绍和运行hello world
    vue学习(一)
    如何用pycharm打开virtualenv、virtualenvwrapper、conda 创建环境
    Android跨进程通信:Binder机制原理
    MapReduce和Spark读取HBase快照表
    《MongoDB》MongoDB的简介与体系结构
    Java并发-线程上下文切换与死锁
    10月10日,每日信息差
  • 原文地址:https://blog.csdn.net/zhangzhanbin/article/details/136300778