一、应用背景
在软件开发中常遇到这种情况,实现某一个功能有多重算法或者策略,我们可以根据不同的场景选择不同的算法或者策略来完成该功能,把一个类(A)中经常改变或者将来可能改变的部分提取出来,作为一个接口B,然后在类A中包含这个接口B,这样类A的实例在运行时就可以随意调用实现了这个接口的类C的行为,比如定义一系列的算法,把每一个算法封装起来,并且把它们可相互替换,使得算法可独立于使用它的客户而变化。这就是策略模式。
二、优缺点
优点:
可以动态的改变对象的行为
缺点:
客户端必须知道所有的策略类,并自行决定使用哪一个策略类
策略模式将产生很多的策略类
三、组成
1、运行环境类: strategy
这个策略模式运行的环境,其实也就是在哪里使用
2、应用场景类:Person
这个就是客户端访问的类,也就是该类的对象所持有的策略
3、具体策略类:Car
具体实现策略类
4、抽象策略类:AbstractCarFunction
根据不同的需求,产生不同的策略或算法的接口
四、代码实现
1、抽象策略类:CarFunction
public interface CarFunction {
void run();
}
2、具体策略父类:Car
public class Car implements CarFunction {
protected String name;
protected String color;
public Car(String name, String color) {
this.name = name;
this.color = color;
}
@Override
public void run() {
System.out.println(color +" " + name +"在行驶。。。");
}
}
3、具体策略实现子类:BussCar SmallCar
public class BussCar extends Car {
public BussCar(String name, String color) {
super(name, color);
}
public void run() {
System.out.println(color +" " + name +"在缓慢的行驶。。。");
}
}
public class SmallCar extends Car{
//具体策略实现子类
public SmallCar(String name, String color) {
super(name, color);
}
public void run() {
System.out.println(color +" " + name +"在高速的行驶。。。");
}
}
4、应用场景类
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//驾驶技能 需要一辆车
public void driver(Car car) {
System.out.print(name +" "+ age+" 岁 "+" 开着");
car.run();
}
}
5、运行环境类:Strategy
public class Strategy {
public static void main(String[] args) {
Car smallCar = new SmallCar("法拉利", "黑色");
Car bussCar = new BussCar("路虎","红色");
Person person = new Person("小王 ", 30);
person.driver(smallCar);
person.driver(bussCar);
}
}
五、总结
策略模式就是老司机会驾驶,今天开路虎,明天开法拉利,针对不同的需求,来使用不同的应对策略,好记一点就是:老司机开车,或者商场不同的产品搞促销等等场景