Java 策略模式

策略模式

策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。

这个模式涉及到三个角色
  • 环境角色

    • 引用者

  • 抽象策略角色

    • 通常由一个接口或者抽象类实现

  • 具体策略

    • 包装相关的算法或者行为

例子

我们模拟一下 两位学生在课间中的行为

Student 类 (引用者)

public class Student {
    
    // 具体策略对象
    private Action action;
​
    public Student( Action action){
        this.action = action;
    }
​
    // 学生的行为
    public void studentAction(){
        action.action();
    }
    
}

Action 接口 (抽象策略角色)

public interface Action {
    //学生的动作
    void action();
}
​

SleepAction类(具体策略)

public class SleepAction implements Action {
    @Override
    public void action() {
        System.out.println("正在睡觉......");
    }
}
​

PlayAction类 (具体策略)

public class PlayAction implements Action {
    @Override
    public void action() {
        System.out.println("正在玩耍.......");
    }
}

Test类(测试类)

public class Test {
    public static void main(String[] args) {
        // 睡觉的行为
        Action sleep = new SleepAction();
        // 玩的行为
        Action play = new PlayAction();
        
        //小明
        Student xiaoming = new Student(sleep);
        xiaoming.studentAction();
        //小明明
        Student mingming = new Student(play);
        mingming.studentAction();
    }
}

结果

正在睡觉......
正在玩耍.......
原文地址:https://www.cnblogs.com/oukele/p/10678661.html