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);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值