由于用户需求的变化,导致经常需要修改类中的某个方法的方法体,即需要不断地变化算法。例如商场商品的打折,会员打折、节日打折、促销打折。这时可以使用策略模式来解决这一问题。
策略模式(Strategy):定义了一系列算法,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
价格策略的接口代码:
package com.psw.strategytest; public interface PriceInterface { //计算价格 double calculatePrice(double goodsPrice); }
package com.psw.strategytest; public class NormalPrice implements PriceInterface { /** * 正常价格,不打折 */ public double calculatePrice(double goodsPrice) { return goodsPrice; } }
package com.psw.strategytest; public class VIPPrice implements PriceInterface { /** * 会员打9折 */ public double calculatePrice(double goodsPrice) { // TODO Auto-generated method stub return goodsPrice*(1.0-0.1); } }
package com.psw.strategytest; public class HolidaySalesPrice implements PriceInterface { /** * 节日促销8折 */ public double calculatePrice(double goodsPrice) { // TODO Auto-generated method stub return goodsPrice*(1.0-0.2); } }
package com.psw.strategytest; public class Goods { private double price; private PriceInterface priceInter; public Goods(PriceInterface priceInter){ this.priceInter = priceInter; } public double getPrice() { return priceInter.calculatePrice(price); } public void setPrice(double price) { this.price = price; } @Override public String toString() { // TODO Auto-generated method stub return price+""; } }
package com.psw.strategytest; public class Main { public static void main(String[] args) { //正常价格 Goods good1 = new Goods(new NormalPrice()); good1.setPrice(98.8); System.out.println("正常价格:" + good1.getPrice()); //VIP价格 Goods good2 = new Goods(new VIPPrice()); good2.setPrice(98.8); System.out.println("VIP价格:" + good2.getPrice()); //节日促销价格 Goods good3 = new Goods(new HolidaySalesPrice()); good3.setPrice(98.8); System.out.println("节日促销价格:" + good3.getPrice()); } }
正常价格:98.8 VIP价格:88.92 节日促销价格:79.04