今天来一起学习下策略模式吧。
提供几种算法,前提是客户端在知道算法的情况下,可以灵活的调用其某个算法。
首先有这几个关键词,算法,行为,具体使用对象。
1.创建一个抽象的折扣类
public interface MemberStrategy {
//计算图书的价格
//bookPrice 图书的原价
// 返回值代表打折后的价格
double calcPrice(double bookPrice);
}
2.创建一个初级会员折扣类
public class PrimaryMemberStrategy implements MemberStrategy{
@Override
public double calcPrice(double bookPrice) {
System.out.println("初级不享受折扣");
return bookPrice;
}
}
3.创建一个中级会员折扣类
public class IntermediateMemberStrategy implements MemberStrategy {
@Override
public double calcPrice(double bookPrice) {
double IntermediatePrice = bookPrice-bookPrice*0.9;
System.out.println("中级享受9折的优惠,优惠了"+IntermediatePrice);
return bookPrice*0.9;
}
}
4.创建一个超级会员折扣类
public class AdvancedMemberStrategy implements MemberStrategy {
@Override
public double calcPrice(double bookPrice) {
double AdvancedPrice = bookPrice-bookPrice*0.8;
System.out.println("高级会员享受优惠,优惠了"+AdvancedPrice);
return bookPrice*0.8;
}
}
5.创建一个具体的策略对象
public class Price {
private MemberStrategy memberStrategy;
public Price(MemberStrategy memberStrategy){
this.memberStrategy = memberStrategy;
}
//计算图书的价格
// bookPrice 图书的原价 返回值代表计算打折后的价格
public double quote(double bookPrice){
return this.memberStrategy.calcPrice(bookPrice);
}
}
6.进行测试
//分别创建各个享受折扣的对象
MemberStrategy memberStrategy1 = new AdvancedMemberStrategy();
MemberStrategy memberStrategy2 = new IntermediateMemberStrategy();
MemberStrategy memberStrategy3 = new PrimaryMemberStrategy();
//创建环境
Price price1 = new Price(memberStrategy1);
Price price2 = new Price(memberStrategy2);
Price price3 = new Price(memberStrategy3);
price1.quote(300);
price2.quote(300);
price3.quote(300);
输出结果:
03-28 23:29:55.945 2948-2948/? I/System.out: 高级会员享受优惠,优惠了60.0
03-28 23:29:55.946 2948-2948/? I/System.out: 中级享受9折的优惠,优惠了30.0
03-28 23:29:55.946 2948-2948/? I/System.out: 初级不享受折扣