码迷,mamicode.com
首页 > 其他好文 > 详细

抽象工厂模式

时间:2015-12-31 00:00:06      阅读:446      评论: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食物接口

 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!