策略模式对应于解决某一个问题的一个算法族,允许用户从该算法族中任选一个算法解决某一问题,同时可以方便的更换算法或者增加新的算法,并且由客户端决定调用那个算法
-- 分离算法,选择实现
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); } }
原文:http://www.cnblogs.com/lipeng0824/p/4442816.html