策略模式对应于解决某一个问题的一个算法族,允许用户从该算法族中任选一个算法解决某一问题,同时可以方便的更换算法或者增加新的算法,并且由客户端决定调用那个算法
本质:
-- 分离算法,选择实现
开发中常见的场景:
代码实现:
package strategy; public interface Strategy { public double getPrice(double standardPrice); }
策略接口
package strategy; public class NewCustomerFewStrategy implements Strategy{ @Override public double getPrice(double standardPrice) { System.out.println("普通顾客小批量购买不打折,原价:"+ standardPrice); return standardPrice; } }
普通用户少批量购买 策略实现
package strategy; public class NewCustomerManyStrategy implements Strategy{ @Override public double getPrice(double standardPrice) { System.out.println("普通顾客大批量购买9折,原价:"+ standardPrice); return standardPrice * 0.9; } }
普通顾客大批量购买
package strategy; public class OldCustomerFewStrategy implements Strategy{ @Override public double getPrice(double standardPrice) { System.out.println("老顾客小批量购买8.5折,原价:" + standardPrice); return standardPrice * 0.85; } }
老顾客小批量购买
package strategy; public class OldCustomerManyStrategy implements Strategy{ @Override public double getPrice(double standardPrice) { System.out.println("老顾客大批量购买8折,原价:"+ standardPrice); return standardPrice * 0.8; } }
老顾客大批量购买
package strategy; public class Client { public static void main(String[] args){ Strategy s1 = new OldCustomerFewStrategy(); Context ctx = new Context(s1); ctx.pringPrice(998); } }
客户端
时间: 2024-10-23 13:18:25