设计模式之策略模式,strategy

来源:互联网 发布:番茄工作法软件 编辑:程序博客网 时间:2024/05/17 22:35
package liu.strategy.demo;
public abstract class CashSuper {
 public abstract double acceptCash(double money);
}
-------------------------------
package liu.strategy.demo;
public class CashNormal1 extends CashSuper{
 @Override
 public double acceptCash(double money) {
  
  return money;
 }
}

-------------------------------
package liu.strategy.demo;
public class CashRebate extends CashSuper{
 private double moneyRebate = 1d;
 @Override
 public double acceptCash(double money) {
  
  return money*moneyRebate;
 }
 
 public CashRebate(String moneyRebate){
  this.moneyRebate = Double.parseDouble(moneyRebate);
 }
 public void setMoneyRebate(double moneyRebate) {
  this.moneyRebate = moneyRebate;
 }
 public double getMoneyRebate() {
  return moneyRebate;
 }
}

-------------------------------
package liu.strategy.demo;
public class CashReturn extends CashSuper{
 private double moneyCondition = 0.0d;
 private double moneyReturn = 0.0d;
 
 public CashReturn(String moneyCondition,String moneyReturn ){
  
  this.moneyCondition = Double.parseDouble(moneyCondition);
  this.moneyReturn = Double.parseDouble(moneyReturn);
 }
 
 
 @Override
 public double acceptCash(double money) {
  double result =money;
  if(money >=moneyCondition){
   result = money - Math.floor(money/moneyCondition)*moneyReturn;
  }
  return result;
 }
}

-------------------------------
package liu.strategy.demo;
public class CashContext {
 private CashSuper cs;
 public CashContext(CashSuper cs){
  this.cs = cs;
 }
 
 public double getResult(double money){
  return cs.acceptCash(money);
 }
}

-------------------------------
package liu.strategy.demo;
public class Main {
 /**
  * 策略模式
  */
 private double total = 0.0d;
 public void btn_click(String sender,double txtPrice,int txtNum){
  CashContext cc = null;
  
  if(sender.equals("正常收费")){
   cc = new CashContext(new CashNormal1());
  }
  else if(sender.equals("满300返100")){
   cc = new CashContext(new CashReturn("300", "100"));
  }
  else{
   cc = new CashContext(new CashRebate("0.8"));
  }
  total = cc.getResult(txtPrice * txtNum)+total;
  System.out.println("单价:"+txtPrice+" 数量:"+txtNum+" 合计:"+(txtPrice * txtNum));
  System.out.println("打折优惠后:"+total);
  
 }
 public static void main(String[] args) {
  
  String sender = "满300返100";
  double txtPrice = 100;
  int txtNum = 6;
  Main test = new Main();
  test.btn_click(sender, txtPrice, txtNum);
 }
}

-------------------------------
Strategy适合下列场合:
1.以不同的格式保存文件;
2.以不同的算法压缩文件;
3.以不同的算法截获图象;
4.以不同的格式输出同样数据的图形,比如曲线或框图bar等
-------------------------------

原创粉丝点击