如果都使用if-else的话,就会使用代码变的臃肿,而且难以复用。那我们就可以根据不同的情况,将不同的方式封装成不同的策略,将策略与它的使用对象分离开来。
案例:
- 定义注解,标注范围
/**
* @author Gjing
* 价格范围注解
**/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PriceRegion {
int min() default 0;
int max() default Integer.MAX_VALUE;
}
- 具体策略
/**
* @author Gjing
* 抽象策略
**/
public interface Price {
BigDecimal getPrice(BigDecimal price);
}
/**
* @author Gjing
* 会员,六折
**/
@PriceRegion(min = 10000,max = 20000)
class Member implements Price {
@Override
public BigDecimal getPrice(BigDecimal price) {
return price.multiply(new BigDecimal(0.6 + ""));
}
}
/**
* @author Gjing
* 普通客户
**/
@PriceRegion(max = 10000)
class Ordinary implements Price {
@Override
public BigDecimal getPrice(BigDecimal price) {
return price;
}
}
/**
* @author Gjing
* 超级会员,4折
**/
@PriceRegion(min = 20000)
class SuperMember implements Price{
@Override
public BigDecimal getPrice(BigDecimal price) {
return price.multiply(new BigDecimal(0.4+""));
}
}
- 策略上下文和策略工厂
/**
* @author Gjing
* 上下文
**/
class PriceContext {
BigDecimal getPrice(BigDecimal costPrice) throws Exception {
Price price = PriceFactory.getInstance().getPrice(costPrice);
return price.getPrice(costPrice);
}
}
/**
* @author Gjing
* 策略工厂
**/
class PriceFactory {
private static final PriceFactory FACTORY = new PriceFactory();
/**
* 策略类集合
*/
private List<Class<? extends Price>> priceList = new ArrayList<>();
private PriceFactory() {
//这边是可以改造成自动获取文件路径的哈
priceList.add(Member.class);
priceList.add(Ordinary.class);
priceList.add(SuperMember.class);
}
/**
* 获取对应金额的策略类
* @param price 金额
* @return Price
* @throws Exception classNotFound
*/
Price getPrice(BigDecimal price) throws Exception{
for (Class<? extends Price> clazz : priceList) {
PriceRegion priceRegion = clazz.getAnnotation(PriceRegion.class);
if (price.compareTo(new BigDecimal(priceRegion.max())) < 0 && price.compareTo(new BigDecimal(priceRegion.min())) > 0) {
return clazz.newInstance();
}
}
return null;
}
static PriceFactory getInstance() {
return FACTORY;
}
}
- 调用:
/**
* @author Gjing
**/
public class Test {
public static void main(String[] args) throws Exception {
PriceContext priceContext = new PriceContext();
System.out.println(priceContext.getPrice(new BigDecimal(200)));
System.out.println(priceContext.getPrice(new BigDecimal(11100)));
System.out.println(priceContext.getPrice(new BigDecimal(30000)));
}
}
以上为个人理解,如有误欢迎各位指正