通过java的抽象类和继承的结合,编写一个“咖啡工厂”的代码
父类:
package com.ty.factory;
public abstract class Coffee {
public abstract String getName(); //定义一个抽象类方法
}
子类:
package com.ty.factory;
public class Latte extends Coffee{ //继承父类的方法
public String getName(){
return "Latte";
}
}
package com.ty.factory;
public class Blackcoffee extends Coffee{ //继承父类的方法
public String getName(){
return "Blackcoffee";
}
}
咖啡工厂:
package com.ty.factory;
public class Coffeefactory {
private Coffee coffee;
public Coffee createCoffee(String type) {
Coffee coffee = null;
if ("Cappuccino".equals(type)) { //构建咖啡对象的属性
coffee = new Cappuccino();
} else if ("Latte".equals(type)) {
coffee = new Latte();
}
return coffee;
}
}
咖啡店铺:
package com.ty.factory;
public class Coffeestore{
private Coffeefactory factory;
public Coffee order(String type){
Coffeefactory factory = new Coffeefactory();
return factory.createCoffee(type);
}
}
用户:
package com.ty.factory;
public class Client {
public static void main(String[] args) {
Coffeestore store = new Coffeestore(); //调用CoffeeFactory的方法
Coffee coffee = store.order("Cappuccino");
System.out.println(coffee.getName());
System.out.println(coffee);
}
}
代码运行如下:
com.ty.Coffeefactory.Client
Blackcoffee
com.ty.Coffeefactory.Cappuccino@4554617c
Process finished with exit code 0