标签:
根据上述要求来用抽象工厂模式设计程序。我将程序放在了https://github.com/RoyalBob/Abstract-Factory-Mode-Practice.git 欢迎访问。
以下是本程序的UML图以及代码:
1、创建一个大的食品工厂接口IFoodFactory
1 public interface IFoodFactory { 2 public Burger MakeBurger(); 3 public Chicken MakeChicken(); 4 public Drink MakeDrink(); 5 }
2、这两家店都有各自的汉堡、炸鸡、饮料,所以创建一个大的食品接口IFood,里面有一个做食物的方法
1 public interface IFood { 2 public abstract void Make(); 3 }
3、汉堡Burger实现IFood食物接口
1 abstract class Burger implements IFood{ 2 3 public void Make() { 4 5 } 6 }
4、炸鸡Chicken实现IFood食物接口
1 abstract class Chicken implements IFood{ 2 3 public void Make() { 4 5 } 6 }
5、饮料Drink实现IFood食物接口
1 abstract class Drink implements IFood{ 2 3 public void Make() { 4 5 } 6 }
6、KFC的汉堡和McDonald‘s的汉堡都继承Burger来生产出各自的汉堡
KFC的汉堡:
1 public class KFCBurger extends Burger{ 2 public void Make() { 3 System.out.println("This is KFC‘s Burger!"); 4 } 5 }
McDonald‘s的汉堡:
1 public class McDonaldBurger extends Burger{ 2 public void Make() { 3 System.out.println("This is McDonal‘s Burger!"); 4 } 5 }
7、KFC的炸鸡和McDonald‘s的炸鸡都继承Chicken来生产出各自的炸鸡
KFC的炸鸡:
1 public class KFCChicken extends Chicken{ 2 public void Make() { 3 System.out.println("This is KFC‘s Chicken!"); 4 } 5 }
McDonald‘s的炸鸡:
1 public class McDonaldChicken extends Chicken{ 2 public void Make() { 3 System.out.println("This is McDonald‘s Chicken!"); 4 } 5 }
8、KFC的饮料和McDonald‘s的饮料都继承Drink来生产出各自的饮料
KFC的饮料:
public class KFCDrink extends Drink{ public void Make() { System.out.println("This is KFC‘s Drink!"); } }
McDonald‘s的饮料:
1 public class McDonaldDrink extends Drink{ 2 public void Make() { 3 System.out.println("This is McDonald‘s Drink!"); 4 } 5 }
9、KFC和McDonald‘s工厂分别去实现这个食品工厂的接口
KFC工厂:
1 public class KFCFactory implements IFoodFactory{ 2 3 public Burger MakeBurger() { 4 return new KFCBurger(); 5 } 6 7 public Chicken MakeChicken() { 8 return new KFCChicken(); 9 } 10 11 public Drink MakeDrink() { 12 return new KFCDrink(); 13 } 14 }
McDonald‘s工厂:
1 public class McDonaldFactory implements IFoodFactory{ 2 3 public McDonaldBurger MakeBurger() { 4 return new McDonaldBurger(); 5 } 6 7 public McDonaldChicken MakeChicken() { 8 return new McDonaldChicken(); 9 } 10 11 public McDonaldDrink MakeDrink() { 12 return new McDonaldDrink(); 13 } 14 15 }
10、书写主函数Main来分别创建KFC和McDonald‘s实例,来制作各自的汉堡、炸鸡和饮料。输出结果看是否符合要求:
标签:
原文地址:http://www.cnblogs.com/RoyalBob/p/4948045.html