用于封装系列的算法,客户端可以自由选择其中一种算法,考虑以下情形:现需要开发一个网上书店,该书店为了更好地促销,经常需要对图书进行打折促销,程序需要考虑各种打折促销的计算方法:
package com.fcy.model;
interface DiscountStrategy{
double getDiscount(double originPrice);
}
class VipDiscount implements DiscountStrategy {
public double getDiscount(double originPrice){
System.out.println("使用vip折扣...");
return originPrice*0.5;
}
}
class OldDiscount implements DiscountStrategy{
public double getDiscount(double originPrice){
System.out.println("使用旧书折扣...");
return originPrice*0.7;
}
}
class DiscountContext{
private DiscountStrategy strategy;
public DiscountContext(DiscountStrategy strategy){
this.strategy=strategy;
}
public double getDiscountPrice(double price){
if(strategy==null){
strategy=new OldDiscount();
}
return this.strategy.getDiscount(price);
}
public void changeDiscount(DiscountStrategy strategy){
this.strategy=strategy;
}
}
public class Strategy {
public static void main(String[] args){
DiscountContext dc=new DiscountContext(null);
double price1=79;
System.out.println("79元图书默认打折后的价格是:"+dc.getDiscountPrice(price1));
dc.changeDiscount(new VipDiscount());
double price2=89;
System.out.println("89元的书对vip用户价格是:"+dc.getDiscountPrice(price2));
}
}
运行结果 :