With the foundation of OO, I began to study the design model carefully! Design patterns are essential in Java design!
Apple.java
package strategy;/** * * @author Andy * */ public class Apple implements Discountable { //Weight private double weight; //The actual unit price is designed and money and other accurate calculations are BigDecimal; private double price; //Discounted by purchase quantity// private Discountor d = new AppleWeightDiscountor(); //Discounted by purchase total price 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 { //Weight private double weight;/////The actual unit price development involves accurate calculations such as money and other things. 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() { //Discount algorithm if(weight < 5) { System.out.println("Banana undiscounted price: " + weight * price); }else if(weight >= 5 && weight < 10) { System.out.println("Banana has 80% discounted price: " + weight * price * 0.88 ); }else if(weight >= 10) { System.out.println("Banana 50% off price: " + weight * price * 0.5 ); } }}Market.java
package strategy;/** * * @author Andy * */public class Market { /** * Discounts for discounted items* @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) {// You can only discount Apple but not general-purpose things, and you write any discount algorithm when you want to sell // In fact, the discount algorithm for each type of thing is inconsistent Discountable d = new Apple(10.3, 3.6); Discountable d1= new Banana(5.4, 1.1); Market.discountSell(d); Market.discountSell(d1); } }