策略接口:
import java.math.BigDecimal;
/**
* 用户支付策略接口
*/
public interface UserPayStrategy {
/**
* 计算应付价格
*/
BigDecimal quote(BigDecimal orderPrice);
}
策略实现类:
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
/**
* 超级VIP支付策略
*/
@Service
public class SuperVipPayStrategy implements UserPayStrategy {
@Override
public BigDecimal quote(BigDecimal orderPrice) {
return orderPrice.multiply(new BigDecimal(0.8));
}
}
///
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
/**
* 普通会员支付策略
*/
@Service
public class NormalVipPayStrategy implements UserPayStrategy{
@Override
public BigDecimal quote(BigDecimal orderPrice) {
return orderPrice.multiply(new BigDecimal(0.9));
}
}
获取策略的工厂:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
// 获取策略的工厂
@Component
public class UserPayServiceStrategyFactory {
@Autowired
private Map<String, UserPayStrategy> userPayStrategyMap;
// 根据 name 获取策略实现,这里可以替换成相应的业务
public UserPayStrategy getUserPayStrategy(String name){
return userPayStrategyMap.get(name);
}
}
通过策略工厂获取需要的策略后,执行业务逻辑:
UserPayStrategy strategy = userPayServiceStrategyFactory.getUserPayStrategy("normalVipPayStrategy");
strategy.quote(new BigDecimal(100)).toPlainString();