策略模式是23种设计模式之一,客户端通过制定多个算法并且封装,使得不同场景可以使用不同的策略算法。使得程序降低了耦合提高代码的复用性。接下来通过一个简单的实例来说明在实战中如何使用(即使是业务逻辑也是可以用设计模式的)。
例子很简单,就是通过同一个保存的service来做不同类型产品的保存。如下图:
接下来看具体实现:
BaseObj:
public abstract class BaseObj implements Serializable {
private Integer id;
private String goodsName;
//省略getter,setter方法
public abstract Byte getType();
}
DiscountGoods:
public class DiscountGoods extends BaseObj implements Serializable{
private double discountRate;
//省略getter,setter方法
public Byte getType() {
return 2;
}
}
StrandardGoods:
public class StrandardGoods extends BaseObj implements Serializable{
public Byte getType() {
return 1;
}
}
BaseSaveService:
public interface BaseService<T> {
Boolean save(T obj);
}
StrandardGoodsService:
@Service
public StrandardGoodsService implements BaseSaveService<StrandardGoods>{
public Boolean save(StrandardGoods goods){
return this.saveStrandardGoods(goods);
}
}
DiscountGoodsService:
@Service
public DiscountGoodsService implements BaseSaveService<DiscountGoods>{
public Boolean save(DiscountGoodsgoods){
return this.saveDiscountGoods(goods);
}
}
StrategyContext:
public StrategyContext {
prviate final Map<BaseObj,BaseSaveService> list=new ConcurrentHashMap<>();
//使用spring注入所有实现了BaseSaveService接口的bean
@Autowired
public StrategyContext (List<BaseSaveService> beansOfType) {
beansOfType.forEach(v -> list.put((BaseObj) v.getEntryInstance(), v));
}
public boolean save(BaseObj baseObj) {
boolean flag = true;
for (Map.Entry<BaseObj, BaseSaveService> entry : list.entrySet()) {
//判断是否对应要保存的具体对象
if (entry.getKey().getClass().isAssignableFrom(baseObj.getClass())) {
flag = entry.getValue().save(baseObj);
}
}
return flag;
}
}
通过与spring结合,以后还会添加不同类型的goods保存只需要添加保存策略,也就是保存的service并不需要改变其他地方的代码就可完成保存。