首頁  >  文章  >  Java  >  Java設計模式之Strategy模式

Java設計模式之Strategy模式

高洛峰
高洛峰原創
2017-01-19 16:24:111517瀏覽

基於有了OO的基礎後,開始認真學習設計模式!設計模式是java設計中不可或缺的!

Apple.java

package strategy;
/**
 *
 * @author Andy
 *
 */
  
public class Apple implements Discountable {
  //重量
  private double weight;
  //单价 实际开发中 设计金钱等精确计算都是BigDecimal;
    private double price;
    //按购买量打折
  // private Discountor d = new AppleWeightDiscountor();
    //按购买总价打折
    private Discountor d = new ApplePriceDiscountor();
      
  public double getWeight() {
    return weight;
  }
    
  public void setWeight(double weight) {
    this.weight = weight;
  }
    
  public double getPrice() {
    return price;
  }
    
  public void setPrice(double price) {
    this.price = price;
  }
 
  public Apple (double weight,double price ){
    
    super();
    this.weight=weight;
    this.price=price;
  }
  
  @Override
  public void discountSell() {
     d.discount(this);
  } 
}

Banana.java

package strategy;
/**
 *
 * @author Andy
 *
 */
public class Banana implements Discountable {
  //重量
  private double weight;
////单价 实际开发中 涉及金钱等精确计算都是用BigDecimal
  private double price;
    
  public Banana(double weight, double price) {
    super();
    this.weight = weight;
    this.price = price;
  }
  
  public double getWeight() {
    return weight;
  }
    
  public void setWeight(double weight) {
    this.weight = weight;
  }
    
  public double getPrice() {
    return price;
  }
    
  public void setPrice(double price) {
    this.price = price;
  }
  
  @Override
  public void discountSell() {
    //打折算法
    if(weight < 5) {
      System.out.println("Banana未打折价钱: " + weight * price);
    }else if(weight >= 5 && weight < 10) {
      System.out.println("Banana打八八折价钱: " + weight * price * 0.88 );
    }else if(weight >= 10) {
      System.out.println("Banana打五折价钱: " + weight * price * 0.5 );
    }   
      
  }
 
}

Market.java

package strategy;
/**
 *
 * @author Andy
 *
 */
public class Market {
    
  /**
   * 对可打折的一类事物进行打折
   * @param apple
   */
 
  public static void discountSell(Discountable d) {
    d.discountSell();
 
}
}

更多Java設計模式之Strategy模式相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn