我们以去KFC订餐为例
步骤1
这是KFC所卖的食物
public class Food {
private String Zhaji;//炸鸡
private String Kele;//可乐
private String Hanbao;//汉堡
public String getZhaji() {
return Zhaji;
}
public void setZhaji(String zhaji) {
Zhaji = zhaji;
}
public String getKele() {
return Kele;
}
public void setKele(String kele) {
Kele = kele;
}
public String getHanbao() {
return Hanbao;
}
public void setHanbao(String hanbao) {
Hanbao = hanbao;
}
}
步骤2
KFC店
public abstract class KFC {
Food food = new Food();
void makeZhaji() {};
void makeKele() {};
void makeHanbao() {};
Food getFood() {
return food;
};
}
步骤3
KFC卖的A套餐
public class KFC_A extends KFC{
@Override
void makeZhaji() {
// TODO Auto-generated method stub
super.makeZhaji();
food.setZhaji("炸全鸡");
}
@Override
void makeKele() {
// TODO Auto-generated method stub
super.makeKele();
food.setKele("小杯可乐");
}
@Override
void makeHanbao() {
// TODO Auto-generated method stub
super.makeHanbao();
food.setHanbao("鸡腿堡");
}
}
B套餐
public class KFC_B extends KFC{
@Override
void makeKele() {
// TODO Auto-generated method stub
super.makeKele();
food.setKele("中杯可乐");
}
@Override
void makeHanbao() {
// TODO Auto-generated method stub
super.makeHanbao();
food.setHanbao("鳕鱼堡");
}
}
步骤4
/**
* 菜单
* @author USER
*
*/
public class KFCMenu {
/**
* A套餐
* @param a
* @return
*/
public Food getA(KFC_A a) {
a.makeHanbao();
a.makeKele();
a.makeZhaji();
return a.getFood();
}
/**
* B套餐
* @param b
* @return
*/
public Food getB(KFC_B b) {
b.makeHanbao();
b.makeKele();
return b.getFood();
}
}
步骤5
测试
KFCMenu menu = new KFCMenu();
//套餐A
Food food_a = menu.getA(new KFC_A());
System.out.println(food_a.getHanbao());
System.out.println(food_a.getKele());
System.out.println(food_a.getZhaji());
System.out.println("==================");
//套餐B
Food food_b = menu.getB(new KFC_B());
System.out.println(food_b.getHanbao());
System.out.println(food_b.getKele());
网友评论