Java – intuition and design principles
•
Java
I have a class hierarchy, like this drink – > coffee – > latte
Drinks:
public abstract class Beverage { private final String name; private final double price; Beverage(String name,double price){ this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } public abstract void make(); }
Coffee:
public abstract class Coffee extends Beverage { public Coffee(String name,double price) { super(name,price); } public final void make(){ grindBeans(); takeShot(); frothMilk(); addCondiments(); } public void grindBeans(){ System.out.println("Grinding Beans..."); } public void takeShot(){ System.out.println("Taking Shot...."); } public abstract void frothMilk(); public abstract void addCondiments(); }
Latte:
public class Latte extends Coffee { public Latte() { super("Latte",4.0); } @Override public void frothMilk() { System.out.println("Frothing milk to create micro foam"); } @Override public void addCondiments() { // TODO Auto-generated method stub } }
Edit: add sugar to an existing structure Only new codes are displayed
public abstract class Beverage { private Sugar sugar; public Sugar getSugar() { return sugar; } public void setSugar(Sugar sugar) { this.sugar = sugar; } }
Coffee:
public abstract class Coffee extends Beverage { public final void make(){ grindBeans(); takeShot(); frothMilk(); addSugar(); addCondiments(); } public void addSugar(){ Sugar sugar = super.getSugar(); if(!(sugar instanceof NoSugar)){ System.out.println("adding " + sugar.getTeaspoon() + " teaspoon sugar"); } }
Solution
Although combination and inheritance have many benefits, using the feeling of inheritance is natural (i.e. in a real relationship) without any problems If it is natural, please continue to use it
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码