策略模式定义:
定义一组算法,将每个算法都封装起来,并且使他们之间可以互换,实际上,就是将每个算法分离出来,定义一个公共的接口,可以选择性的实现功能,这就是策略模式。
策略模式使用场景和结构:
应用场景:
可以应用在商场打折促销活动,例如 六一期间,商场搞促销活动,会员8折 ,普通客户不打折等等。
结构:
1、公共策略:定义一个接口作为公共策略,所有的算法规则实现该接口;
2、具体策略:封装了具体的算法和行为,继承于公共策略;
3、封装类:进行二次封装,维护对公共策略对象的引用;
代码演示:
优惠策略定义:
package com.lzw.strategy;
import java.math.BigDecimal;
/**
* 优惠策略
* @author lzw
* @Date 2019年5月30日
*/
public interface PreferentialStrategy {
BigDecimal getPrice(BigDecimal originalPrice);
}
普通顾客优惠策略:
package com.lzw.strategy;
import java.math.BigDecimal;
/**
* 普通顾客优惠策略
* @author lzw
* @Date 2019年5月30日
*/
public class OrdinaryCustomer implements PreferentialStrategy {
@Override
public BigDecimal getPrice(BigDecimal originalPrice) {
System.out.println("普通顾客没有优惠");
return originalPrice;
}
}
VIP会员客户优惠策略:
package com.lzw.strategy;
import java.math.BigDecimal;
/**
* VIP会员顾客优惠策略
* @author lzw
* @Date 2019年5月30日
*/
public class VIPCustomer implements PreferentialStrategy {
@Override
public BigDecimal getPrice(BigDecimal originalPrice) {
System.out.println("VIP会员客户享有9折优惠");
originalPrice = originalPrice.multiply(new BigDecimal(0.9)).setScale(2,BigDecimal.ROUND_HALF_UP);
return originalPrice;
}
}
MVP会员客户优惠策略:
package com.lzw.strategy;
import java.math.BigDecimal;
/**
* MVP会员顾客优惠策略
* @author lzw
* @Date 2019年5月30日
*/
public class MVPCustomer implements PreferentialStrategy {
@Override
public BigDecimal getPrice(BigDecimal originalPrice) {
System.out.println("MVP会员客户享有8折优惠!");
originalPrice = originalPrice.multiply(new BigDecimal(0.8)).setScale(2,BigDecimal.ROUND_HALF_UP);
return originalPrice;
}
}
钻石会员客户优惠策略:
package com.lzw.strategy;
import java.math.BigDecimal;
/**
* 钻石会员顾客优惠策略
* @author lzw
* @Date 2019年5月30日
*/
public class DiamondCustomer implements PreferentialStrategy {
@Override
public BigDecimal getPrice(BigDecimal originalPrice) {
System.out.println("钻石会员客户享有5折优惠!");
originalPrice = originalPrice.multiply(new BigDecimal(0.5)).setScale(2,BigDecimal.ROUND_HALF_UP);
return originalPrice;
}
}
优惠上下文:
package com.lzw.strategy;
import java.math.BigDecimal;
/**
* 优惠上下文
* @author lzw
* @Date 2019年5月30日
*/
public class PreferentialContent {
private PreferentialStrategy priceIStrategy;
//注入优惠策略
public PreferentialContent(PreferentialStrategy priceIStrategy){
this.priceIStrategy = priceIStrategy;
}
//回调具体优惠策略的方法
public BigDecimal getPrice(BigDecimal bigDecimal){
return priceIStrategy.getPrice(bigDecimal);
}
}
客户端:
package com.lzw.strategy;
import java.math.BigDecimal;
/**
* @author lzw
* @Date 2019年5月30日
*/
public class Client {
public static void main(String[] args) {
VIPCustomer vipCustomer = new VIPCustomer();
PreferentialContent content = new PreferentialContent(vipCustomer);
BigDecimal price = content.getPrice(new BigDecimal(1000));
System.out.println("折扣优惠价:"+price);
}
}
控制台打印:
VIP会员客户享有9折优惠
折扣优惠价:900.00
优缺点总结:
1、具有很高的拓展性;
2、可以避免esleif这种多重条件语句;
3、可以通过抽象、封装定义一系列的算法,使它们之间相互替换,为外界提供统一的公共接口。