星巴克要订做一个管理系统.他们的咖啡有不同的品牌,有latte(拿铁),卡布奇诺(cappuccino)等等当然以后肯定会改变,同时各种咖啡都可以加上milk(牛奶),soy(豆浆),sugar(糖)等配料,当然配料也会改变(一杯咖啡可以加两分牛奶).还有咖啡有大杯小杯.
一个coffee父类,各种品牌的开发继承之. 语言是苍白的 看代码!
public class Coffee { private String description; //品牌描述 private String size; private int milk; private int sugar; public Coffee(){ //构造函数 description="unknow coffee"; size="small"; } public Coffee(int milk,int sugar,String size,String brand){ this.milk=milk; this.sugar=sugar; this.size=size; description=brand; } public String getDescription(){ return description+" "+size+"杯咖啡 milk:"+milk+"份 sugar:"+sugar+"份"; } public double cost(){ if(size.equals("small")) //小杯大杯分开 return milk*1.1+sugar*1.2; if(size.equals("jourm")) return milk*1.2+sugar*1.4; return 0; } }然后就是一个拿铁(iatte)继承了coffee 别的品牌都一样的
public class iatte1 extends Coffee{ public double cost(){ return super.cost()+2.5; } public iatte1(int milk,int sugar,String size) { super(milk, sugar, size, "iatte"); } }再看测试类
import condiment.*; import base.Beverage; import brand.*; public class test { public static void main(String[] args){ Coffee aCoffee=new iatte1(2,3,"small"); System.out.println(aCoffee.getDescription()); System.out.println(aCoffee.cost()); } }测试结果
package base; public abstract class Beverage { public String description="unknow coffee"; public String size="unknow size"; public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public abstract double cost(); }
package brand; import base.Beverage; public class latte extends Beverage{ public double cost() { if(size.endsWith("jorum")) return 1.5; else if(size.endsWith("small")) return 1.2; return 1.2; } public latte(){ size="jorum"; description="latte jorum coffee"; } public latte(String size2){ size=size2; description="latte "+size+" coffee"; } }其他品牌类似,不在赘述.
package condiment; import base.Beverage; public abstract class condiment extends Beverage { public abstract String getDescription(); }
package condiment; import base.Beverage; public class sugar extends condiment { Beverage beverage; public sugar(Beverage beverage2){ beverage=beverage2; } public String getDescription() { System.out.print("suga 的形容 \n"); return beverage.getDescription()+" ,sogar"; } public double cost() { return beverage.cost()+2.4; } }
import condiment.*; import base.Beverage; import brand.*; public class test { public static void main(String[] args){ System.out.println("第一杯"); Beverage aBeverage=new latte(); System.out.println(aBeverage.getDescription()); System.out.println(aBeverage.cost()); System.out.println(); System.out.println("第二杯"); Beverage bBeverage=new cappuccino("small"); bBeverage=new milk(bBeverage); bBeverage=new milk(bBeverage); bBeverage=new sugar(bBeverage); System.out.println(bBeverage.getDescription()); System.out.println(bBeverage.cost()); } }