策略模式将具体的算法封装到独立的类中,当我们需要使用不同的策略时,只需要给执行对象提供不同的策略就行了。
场景:VR是现在很火的产品,一套好的VR设备是十分昂贵的,在初期由于市场供不应求,可能买来设备的价格高于官方报价。过了一段时间,卖家会降价,再过段时间,VR的势头过去,堆积的商品会进行促销。
这个时候我们就可以使用策略模式,在不同时期,对于商品使用不同的价格策略来对价格进行调控。
优点:
//一个方法,有很多个业务场景,继承后业务不同,子类可能就需要重写很多地方
public abstract class Bird {
public void fly() {
System.out.print("fly");
}
}
// 有些鸭子不会飞
// 由于父类方法的继承性这个时候如果大量子类需要对fly重写为cant fly就会改很多地方,100个就改100次
public class Bird extends Bird {
public void fly() {
System.out.print("cant fly");
}
}
// 那么考虑接口形式,那么当实现类很多的时候,每个都要实现接口,100个也就100次,这里就不扩展代码了
角色 |
作用 |
---|---|
环境(Context) |
持有一个(Strategy)的引用 |
抽象策略(Strategy) |
定义所有的具体策略类所需的实现的方法 |
具体策略(ConcreteStrategy) |
实现具体方法,定义方法中的具体算法 |
策略基类
提供降价接口
public interface Strategy {
public double offerPrice(double orgPrice);
}
小幅度降价:打8折
public class DepreciateStrategy implements Strategy {
@Override
public double offerPrice(double orgPrice) {
System.out.println("现在商品小降价");
return .8 * orgPrice;
}
}
提价:供不应求.为原价的1.2倍
public class RaiseStrategy implements Strategy {
@Override
public double offerPrice(double orgPrice) {
System.out.println("现在商品抬价");
return 1.2 * orgPrice;
}
}
促销价:为原价的一半
public class PromotionStrategy implements Strategy {
@Override
public double offerPrice(double orgPrice) {
System.out.println("现在商品促销价");
return .5 * orgPrice;
}
}
VR设备:环境类
public class VR{
public double orgPrice = 10000.0; // 商品官方的报价
private Strategy strategy;
public VR(Strategy strategy) {
this.strategy = strategy;
}
public double getPrice() {
return strategy.offerPrice(orgPrice);
}
}
场景应用
public static void main(String[] args) {
Strategy sg1 = new RaiseStrategy();
VR vr1 = new VR(sg1);
System.out.println(vr1.getPrice());
Strategy sg2 = new DepreciateStrategy();
VR vr2 = new VR(sg2);
System.out.println(vr2.getPrice());
Strategy sg3 = new PromotionStrategy();
VR vr3 = new VR(sg3);
System.out.println(vr3.getPrice());
}
输出
现在商品抬价
12000.0
现在商品小降价
8000.0
现在商品促销价
5000.0
状态模式:
状态模式处理的核心问题是状态的迁移,因为在对象存在很多状态情况下,各个状态之间跳转和迁移过程都是及其复杂的。在状态模式中,状态改变是由对象的内部条件决定,外界只需关心其接口,不必关心其状态对象的创建和转化。
策略模式:
策略模式的好处在于你可以动态的改变对象的策略行为。策略模式里,采取何种策略由外部条件决定,也就是说使用什么策略由我们来提供,而策略的具体实现类实现对应算法。比如一种商品,我们可以有很多降价和提价策略,我们只需要定义好各种策略的规则,然后让商品去执行就行了。
提枪策马乘胜追击04-21 20:01
代码小兵87207-15 12:10
杨晶珍05-11 14:54
杨晶珍05-12 17:30