折扣策略接口
public interface DiscountStrategy {
/**
* 计算价格
*/
public double calcPrice(double booksPrice);
}
普通会员折扣
public class NormalStrategy implements DiscountStrategy {
@Override
public double calcPrice(double price) {
System.out.println("普通会员的没有折扣");
return price;
}
}
中级会员折扣
public class MiddleStrategy implements DiscountStrategy {
@Override
public double calcPrice(double price) {
System.out.println("中级会员9折");
return price * 0.9;
}
}
高级会员折扣
public class HighStrategy implements DiscountStrategy {
@Override
public double calcPrice(double price) {
System.out.println("高级会员8折");
return price * 0.8;
}
}
价格类
public class Price {
//持有一个具体的策略对象
private Strategy strategy;
/**
* 构造函数,传入一个具体的策略对象
* @param strategy 具体的策略对象
*/
public Price(Strategy strategy){
this.strategy = strategy;
}
/**
* 计算价格
*/
public double getFinalPrice(double price){
return this.strategy.calcPrice(price);
}
}
场景类
public class Client {
public static void main(String[] args) {
//选择并创建需要使用的策略对象
Strategy strategy = new MiddleStrategy();
//创建环境
Price price = new Price(strategy);
//计算价格
double finalPrice = price.getFinalPrice(300);
System.out.println("最终价格为:" + finalPrice);
}
}