1创建食物抽象方法
public abstract class Food implements Cloneable {
String name;
String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getClone() {
Object o=null;
try {
o=super.clone();
} catch (Exception e) {
e.printStackTrace();
}
return o;
}
}
2创建菜单实现类
public class RoastDuck extends Food {
public RoastDuck(){
type="鸭子";
}
}
public class SteamedBum extends Food{
public SteamedBum(){
type="面粉,猪肉";
}
}
3 创建食谱
import java.util.HashMap;
public class Menu {
private static HashMap<String,Food> menuList=new HashMap<String,Food>();
public static void getMenuList(){
RoastDuck rd=new RoastDuck();
rd.setName("烤鸭");
menuList.put(rd.getName(), rd);
SteamedBum sb=new SteamedBum();
sb.setName("包子");
menuList.put(sb.getName(), sb);
}
public static Food getFoodType(String name){
Food food=menuList.get(name);
return (Food)food.getClone();
}
}
4调用
Menu.getMenuList();
Food food1=Menu.getFoodType("烤鸭");
System.out.println(food1.getType());
Menu.getMenuList();
Food food2=Menu.getFoodType("包子");
System.out.println(food2.getType());