定义一个接口IFood,该接口有一个抽象方法 public abstract eat
定义Bread和Milk类来实现IFood的抽象方法,定义一个Factory工厂类,并且在此类中提供有一个静态方法可以用于返回IFood接口实例化对象。
1)IFood接口
class Bread implements IFood{
@Override
public void eat() {
System.out.println("正在吃面包");
}
}
2)Milk类
class Milk implements IFood{
@Override
public void eat() {
System.out.println("正在喝牛奶");
}
}
3)面包类
class Bread implements IFood{
@Override
public void eat() {
System.out.println("正在吃面包");
}
}
4)工厂类
class Factory{
public static IFood getInstance(String foodName) {
if("bread".equals(foodName))
return new Bread();
else if("milk".equals(foodName))
return new Milk();
else return null;
}
}
5)主方法
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
String food = scan.next();
IFood f =Factory.getInstance(food);
f.eat();
}