策略模式

78 阅读1分钟

在Java策略模式的精髓就是使用接口做聚合,具体的行为交给你所选择的实现类

对于策略模式的定义我们需要一个官方的解释,确保准确凝练

策略模式(Strategy Pattern) :定义一系列算法类,将每一个算法封装起来,并让它们可以相互替换,策略模式让算法独立于使用它的客户端而变化,也称为政策模式(Policy)。

现在我们需要一个图来对上面的概念进行解释,所以我从网上找了别人的一个图

image.png

每个算法封装起来”其实就是不同的策略类 ConcreteStrategyA ConcreteStrategyB,而“算法”就是 excute()方法里的内容,“相互替换”是因为聚合了接口类

下面举一个代码的例子:

interface Weapon {
    void attack();
}
class Gun implements Weapon {
    @Override public void attack() {
        System.out.println("Gun Attacking...");
    }
}
class Knife implements Weapon {
    @Override public void attack() {
        System.out.println("Knife Attacking..."); 
    }
}
class Person {
    private Weapon weapon;
    public Person(Weapon weapon) {
        this.weapon = weapon;
}
    public void attackOthers() {
        weapon.attack(); 
}
    public void changeWeapon(Weapon weapon){
        this.weapon = weapon; 
    } 
}
public class TestStrategy {
    public static void main(String[] args) {// 初始化武器和角色 
    System.out.println("----Game Begin!----");
    Weapon gun = new Gun();
    Weapon knife = new Knife();
    System.out.println("----Alice enter the game with a knife----");
    Person alice = new Person(knife);
    System.out.println("----Bob enter the game with a gun----");
    Person bob = new Person(gun); // Alice用刀偷袭了Bob 
    System.out.println("----Alice attack Bob----"); 
    alice.attackOthers(); // Bob发现有人偷袭,转身给对方一枪 
    System.out.println("----Bob attack Alice----");
    bob.attackOthers(); // Alice发现刀的杀伤力不够,更换枪
    System.out.println("----Alice change weapon to gun----");
    alice.changeWeapon(gun); // Alice更换枪后,给Bob致命一击 
    System.out.println("----Alice attack Bob----"); 
    alice.attackOthers(); 
    System.out.println("----Game Over! Alice Win!----"); 
    } 
}

那策略模式应用场景有哪些呢

  • 1、线程池的拒绝策略

  • 2、在spring应用最广发的依赖注入,注入的是接口,具体实现类使用是再指定