首页 > 其他 > 详细

抽象工厂模式

时间:2015-12-31 00:08:37      阅读:222      评论:0      收藏:0      [点我收藏+]

技术分享

程序的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食物接口

炸鸡Chicken的IFood食物接口

饮料Drink的IFood食物接口

 abstract class Burger implements IFood
{
     public void Make() {       
     }
 }
 abstract class Burger implements IFood
{
     public void Make() {       
     }
 }

 abstract class Chicken 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来生产肯德基和麦当劳的炸鸡,继承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!");
     }
 }
//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/gzy1031/p/5090388.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!