1:策略模式
运行时根据条件的不同使用不同的策略处理一个事情。
1:创建策略类
public interface MemberStrategy {
public double calcPrice(double booksPrice);
}
2:创建不同的策略处理对象
public class AdavaceMember implements MemberStrategy{
@Override
public double calcPrice(double booksPrice) {
System.out.println("对于高级会员的折扣为50%");
return booksPrice*0.5;
}
}
public class MediumMember implements MemberStrategy{
@Override
public double calcPrice(double booksPrice) {
System.out.println("对于高级会员的折扣为60%");
return booksPrice*0.6;
}
}
3:定义具体的场景
public class Price {
private MemberStrategy ms;
public Price(MemberStrategy ms){
this.ms=ms;
}
//场景里面也具备了策略里面的方法
public double quote(double booksPrice){
return this.ms.calcPrice(booksPrice);
}
}
4:测试
public class Price {
private MemberStrategy ms;
public Price(MemberStrategy ms){
this.ms=ms;
}
public double quote(double booksPrice){
return this.ms.calcPrice(booksPrice);
}
}