栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java设计模式之Strategy模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java设计模式之Strategy模式

基于有了OO的基础后,开始认真学习设计模式!设计模式是java设计中必不可少的!

Apple.java

package strategy;

 
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;

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;

public class Market {
   
  

  public static void discountSell(Discountable d) {
    d.discountSell();

}
}

Discountable.java

package strategy;

public interface Discountable {
  public void discountSell();
}

Test.java

package strategy;

public class Test {
   
  
 
  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);
     
 
  }
 
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/149582.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号