给你写了:
首先是一个Drink接口:
public interface Drink {
void taste();
}
接着是三个子类
public class Coffee implements Drink{
@Override
public void taste() {
System.out.println("咖啡:苦");
}
}
public class Beer implements Drink{
@Override
public void taste() {
System.out.println("啤酒:略微苦涩");
}
}
public class Milk implements Drink {
@Override
public void taste() {
System.out.println("牛奶:微甜");
}
}
然后是Drink工厂类,通过这个类中的方法根据传入参数获取不同的饮料类型
public class DrinkFactory {
public static Drink getDrink(String drinkType){
if (drinkType==null){
return null;
}
if(drinkType.equalsIgnoreCase("Coffee")){
return new Coffee();
}else if(drinkType.equalsIgnoreCase("Beer")){
return new Beer();
}else if(drinkType.equalsIgnoreCase("Milk")){
return new Milk();
}
return null;
}
}
最后测试类:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//命令行输入参数
System.out.println("请输入饮料类型:");
Scanner scanner = new Scanner(System.in);
String next = scanner.next();
Drink drink = DrinkFactory.getDrink(next);
if(drink==null){
System.out.println("对不起!没有您输入的饮料类型。");
}else {
drink.taste();
}
}
}
打完收工