>  기사  >  Java  >  자바 디자인 패턴 전략 패턴

자바 디자인 패턴 전략 패턴

高洛峰
高洛峰원래의
2017-01-19 16:24:111477검색

OO의 기초를 바탕으로 본격적으로 디자인 패턴 학습을 시작해 보세요! 자바 디자인에서 디자인 패턴은 필수!

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

Discountable.java

package strategy;
/**
 *
 * @author Andy
 *
 */
public interface Discountable {
  public void discountSell();
}

Test.java

package strategy;
/**
 *
 * @author Andy
 *
 */
public class Test {
    
  /**
   *
   * @param args
   */
  
  public static void main(String[] args) {
//    只能对苹果打折 还不能对通用的一类事物打折 而且都是要卖什么就写什么打折算法
//   其实每类事物打折算法又是不一致的
    Discountable d = new Apple(10.3, 3.6);
    Discountable d1= new Banana(5.4,1.1);
      Market.discountSell(d);
      Market.discountSell(d1);
      
  
  }
  
}

Java 디자인 패턴의 전략 모드와 관련된 더 많은 기사를 보려면 다음을 참조하세요. PHP 중국어 넷에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.