23大设计模式之策略模式

策略模式
每个算法都有自己的类

只要在分析过程中需要在不同时间应用不同的业务规则时,可以考虑用这个模式




package com.test.two;
public class Cart {
private int count;
private double perMoney;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getPerMoney() {
return perMoney;
}
public void setPerMoney(double perMoney) {
this.perMoney = perMoney;
}

}




package com.test.two;
public abstract class Statege {
abstract double getResult(Cart cart);

}



package com.test.two;
public class StategeSale extends Statege{
double getResult(Cart cart) {
return cart.getCount()*cart.getPerMoney()*0.5;
}

}


package com.test.two;
public class StategeSale2 extends Statege{
double getResult(Cart cart) {
return cart.getCount()*cart.getPerMoney()*0.8;
}

}



package com.test.two;
import java.math.BigDecimal;
public class CartFactory {
public double getResult(Cart cart,String type){
double result=0;
Statege statege=null;
switch (type) {
case "打五折":
statege=new StategeSale();
break;
case "打八折":
statege=new StategeSale2();
break;
default:
return 0;
}
result=statege.getResult(cart);
double value =new BigDecimal(result).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();  
return value;
}

}


package com.test.two;
public class testMain {
public static void main(String[] args){
//正常收费 打八折 打五折 打七者
String type="打八折";
Cart cart=new Cart();
cart.setCount(1);
cart.setPerMoney(12);
CartFactory factory=new CartFactory();
double result= factory.getResult(cart,type);
System.out.print(result);
}
}

猜你喜欢

转载自blog.csdn.net/weixin_40839342/article/details/80626307