基于有了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); } }新聞熱點
疑難解答