标签:
程序的UML图和代码:
(1)先创建一个食品工厂接口IFoodFactory
public interface IFoodFactory { public Burger MakeBurger(); public Chicken MakeChicken(); public Drink MakeDrink(); }
(2)由于两家店都有汉堡、炸鸡和饮料,因此创建一个食品接口IFood,里面有做食物的方法
public interface IFood
{ public abstract void Make(); }
(3)设置各个食物的接口
汉堡Burger的IFood食物接口
abstract class Burger implements IFood { public void Make() { } }
炸鸡Chicken的IFood食物接口
abstract class Chicken implements IFood { public void Make() { } }
饮料Drink的IFood食物接口
abstract class Drink implements IFood { public void Make() { } }
(4)继承Burger来生产肯德基和麦当劳的汉堡
public class KFCBurger extends Burger { public void Make() { System.out.println("This is KFC‘s Burger!"); } }
public class McDonaldBurger extends Burger { public void Make() { System.out.println("This is McDonal‘s Burger!"); } }
(5)继承Chicken来生产肯德基和麦当劳的炸鸡
public class KFCChicken extends Chicken { public void Make() { System.out.println("This is KFC‘s Chicken!"); } }
public class McDonaldChicken extends Chicken { public void Make() { System.out.println("This is McDonald‘s Chicken!"); } }
(6)继承Drink来生产肯德基和麦当劳的饮料
public class KFCDrink extends Drink { public void Make() { System.out.println("This is KFC‘s Drink!"); } }
public class McDonaldDrink extends Drink { public void Make() { System.out.println("This is McDonald‘s Drink!"); } }
(7)肯德基和麦当劳 分别实现食品工厂的接口
KFC:
public class KFCFactory implements IFoodFactory { public Burger MakeBurger() { return new KFCBurger(); } public Chicken MakeChicken() { return new KFCChicken(); } public Drink MakeDrink() { return new KFCDrink(); } }
McDonald‘s:
public class McDonaldFactory implements IFoodFactory { public McDonaldBurger MakeBurger() { return new McDonaldBurger(); } public McDonaldChicken MakeChicken() { return new McDonaldChicken(); } public McDonaldDrink MakeDrink() { return new McDonaldDrink(); } }
(8)主函数Main分别创建KFC和McDonald‘s的实例,制作各自的汉堡、炸鸡、饮料。
显示结果如下:
标签:
原文地址:http://www.cnblogs.com/stoneblogs/p/5090255.html