欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java设计模式之Strategy模式

程序员文章站 2024-03-13 13:49:39
基于有了oo的基础后,开始认真学习设计模式!设计模式是java设计中必不可少的! apple.java package strategy; /** *...

基于有了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();

}
}

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