策略模式的定义:
定义一组算法,将每个算法都封装起来,使得它们之间可以相互替换。策略模式让算法独立于调用它的客户端而独立变化。
策略模式包含三个角色:
抽象策略(Strategy):通常由接口或抽象类实现。定义了多个具体策略的公共接口,具体策略类中各种不同的算法以不同的方式实现这个接口;Context使用这些接口调用不同实现的算法。
具体策略(ConcreteStrategy):实现Strategy接口或继承于抽象类Strategy,封装了具体的算法和行为。
环境类(Contex):持有一个公共策略接口的引用,直接给客户端调用。
策略模式具体实现
给策略对象(枪)定义一个公共接口
public interface Weapon {
public void gun();
}
定义具体的策略类(ConcreteStrategy),实现上面的接口
public class FirstGun implements Weapon {
@Override
public void gun() {
System.out.println("使用AWM狙击步枪。");
}
}
public class SecondGun implements Weapon {
@Override
public void gun() {
System.out.println("使用S12K。");
}
}
定义一个环境类(Contex),类中持有一个对公共接口的引用,以及相应的get、set方法、构造方法
public class Context {
Weapon weapon;
public Context(Weapon weapon) { //构造函数
super();
this.weapon = weapon;
}
public Weapon getWeapon() { //get方法
return weapon;
}
public void setWeapon(Weapon weapon) { //set方法
this.weapon = weapon;
}
public void gun() {
weapon.gun();
}
}
客户端自由调用策略(我在枪林弹雨的战场上,切换武器,击毙敌人)
public class StrategyClient {
public static void main(String[] args) {
//使用构造函数默认选择一把AWM狙击步枪(一个策略)
Context context=new Context(new FirstGun());
context.gun();
//使用get、set方法切换到S12K(切换策略)
System.out.println("------右前方30米发现敌人------");
contex.set(new SecondGun());
context.gun();
}
}
参考