创建一个咖啡工厂管理系统,
首先创建三级目录及类
接着就是创建各类需要的代码:
package com.java.Coffee;
public abstract class Coffee {
public abstract String getName();
public void add(){
System.out.println("加点Milk");
}
}
package com.java.Coffee;
public class Latter extends Coffee{
public String getName(){
return "拿铁";
}
}
package com.java.Coffee;
public class BlackCoffee extends Coffee {
public String getName(){
return "BlackCoffee";
}
}
接着是咖啡商店:
package com.java.Coffee;
public class CoffeeStore {
public Coffee orderCoffee(String type){
CoffeeFactory fectory = new CoffeeFactory();
Coffee coffee = fectory.creatCoffee(type);
return coffee;
}
}
再者是咖啡生产工厂:
package com.java.Coffee;
public class CoffeeFactory {
public Coffee creatCoffee(String type){
Coffee coffee = null;
if("Black".equals(type)){
coffee = new BlackCoffee();
}
else if("Latter".equals(type)){
coffee = new Latter();
}
return coffee;
}
}
最后是创建操作代码:
package com.java.Coffee;
public class Client {
public static void main(String[] args) {
CoffeeStore store = new CoffeeStore();
Coffee coffee = store.orderCoffee("Black");
System.out.println(coffee.getName());
coffee.add();
}
}
运行就OK
用到java的继承,还不是很熟练还是需要多加练习。