定义接口:
// 咖啡制作接口
interface CoffeeMaker {
Coffee makeCoffee(String type);
}
// 咖啡店接口
interface CoffeeShop {
void orderCoffee(String type, CoffeeConsumer consumer);
}
// 咖啡消费者接口
interface CoffeeConsumer {
void receiveCoffee(Coffee coffee);
}
// 咖啡类
class Coffee {
private String type;
public Coffee(String type) {
this.type = type;
}
@Override
public String toString() {
return "Coffee of type: " + type;
}
}
实现接口:
// 咖啡工厂实现类
class CoffeeFactory implements CoffeeMaker {
@Override
public Coffee makeCoffee(String type) {
System.out.println("CoffeeFactory is making a coffee of type: " + type);
return new Coffee(type);
}
}
// 咖啡店实现类
class LocalCoffeeShop implements CoffeeShop {
private final CoffeeMaker coffeeMaker;
public LocalCoffeeShop(CoffeeMaker coffeeMaker) {
this.coffeeMaker = coffeeMaker;
}
@Override
public void orderCoffee(String type, CoffeeConsumer consumer) {
System.out.println("LocalCoffeeShop is ordering a coffee of type: " + type);
Coffee coffee = coffeeMaker.makeCoffee(type);
consumer.receiveCoffee(coffee);
}
}
// 用户实现类
class CoffeeLover implements CoffeeConsumer {
@Override
public void receiveCoffee(Coffee coffee) {
System.out.println("CoffeeLover received: " + coffee);
}
}
测试程序:
public class CoffeeFlowDemo {
public static void main(String[] args) {
// 创建咖啡工厂
CoffeeMaker coffeeMaker = new CoffeeFactory();
// 创建咖啡店
CoffeeShop coffeeShop = new LocalCoffeeShop(coffeeMaker);
// 创建用户
CoffeeConsumer coffeeLover = new CoffeeLover();
// 咖啡店订购咖啡并给用户
coffeeShop.orderCoffee("Latte", coffeeLover);
}
}
CoffeeMaker
接口定义了制作咖啡的方法,CoffeeShop
接口定义了订购咖啡的方法,CoffeeConsumer
接口定义了接收咖啡的方法。CoffeeFactory
、LocalCoffeeShop
和CoffeeLover
分别实现了这些接口,并模拟了咖啡制作、订购和接收的流程。
总结:今天老师讲到的接口有一点理解不过来,只理解了一个大概,java的世界从接口开始,理解接口才能够真正学会java,看来得多敲代码了。