设计模式-策略模式
定义一个策略接口
public interface PayStrategy {
void pay(BigDecimal price);
}
具体策略的实现
public class WxPay implements PayStrategy {
@Override
public void pay(BigDecimal price) {
System.out.println("微信支付" + price + "元");
}
}
public class ZfbPay implements PayStrategy {
@Override
public void pay(BigDecimal price) {
System.out.println("支付宝支付" + price + "元");
}
}
策略的入口
public class Mall {
private PayStrategy payStrategy;
private BigDecimal price;
public Mall factory(String payType) {
if ("WX".equals(payType)) {
this.payStrategy = new WxPay();
} else if ("ZFB".equals(payType)) {
this.payStrategy = new ZfbPay();
}
return this;
}
public Mall setPrice(BigDecimal price) {
this.price = price;
return this;
}
public void pay() {
payStrategy.pay(price);
}
}
测试
public class Demo {
public static void main(String[] args) {
new Mall().factory("WX").setPrice(new BigDecimal(1000)).pay();
new Mall().factory("ZFB").setPrice(new BigDecimal(2000)).pay();
}
}