M_K抽象工厂模式

分析:产品之间存在着共性——需引入接口

            ——定义共性——抽象产品类

     工厂共同实现的接口——定义共同接口——抽象工厂类

相关UML图:

类总括:

具体代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace M_K
{
class Program
{
static void Main(string[] args)
{//client
IFactory factory = new KFactory();

FastFood fastfood1 = new FastFood();
fastfood1.Burger = factory.MakeBurger();
fastfood1.Chicken = factory.MakeChicken();
fastfood1.Drink = factory.MakeDrink();
fastfood1.Eat();

FastFood fastfood2 = new FastFood();
fastfood2.Burger = factory.MakeBurger();
fastfood2.Chicken = factory.MakeChicken();
fastfood2.Drink = factory.MakeDrink();
fastfood2.Eat();

Console.ReadLine();
}
}
}
interface IFactory
{//接口
Burger MakeBurger();
Chicken MakeChicken();
Drink MakeDrink();
}
class KFactory : IFactory
{//具体工厂KFC
public Burger MakeBurger()
{
return new KBurger();
}

public Chicken MakeChicken()
{
return new KChicken();
}

public Drink MakeDrink()
{
return new KDrink();
}
}
class MFactory : IFactory
{//具体工厂MCD
public Burger MakeBurger()
{
return new MBurger();
}

public Chicken MakeChicken()
{
return new MChicken();
}

public Drink MakeDrink()
{
return new MDrink();
}
}
abstract class Burger
{//抽象产品Burger
public abstract void GainB();
}
abstract class Chicken
{//抽象产品Chicken
public abstract void GainC();
}
abstract class Drink
{//抽象产品Drink
public abstract void GainD();
}
class KBurger : Burger
{//具体产品KBurger
public override void GainB()
{
Console.WriteLine("KFC Burger is yummy...");
}
}
class MBurger : Burger
{//具体产品MBurger
public override void GainB()
{
Console.WriteLine("MCD Burger is yummy...");
}
}
class KChicken : Chicken
{//具体产品KChicken
public override void GainC()
{
Console.WriteLine("KFC Chicken is yummy...");
}
}
class MChicken : Chicken
{//具体产品MChicken
public override void GainC()
{
Console.WriteLine("MCD Chicken is yummy...");
}
}
class KDrink : Drink
{//具体产品KDrink
public override void GainD()
{
Console.WriteLine("KFC Drink is yummy...");
}
}
class MDrink : Drink
{//具体产品MDrink
public override void GainD()
{
Console.WriteLine("MCD Drink is yummy...");
}
}
class FastFood
{
private Burger _burger;
private Chicken _chicken;
private Drink _drink;

public Burger Burger
{
get { return _burger; }
set { _burger = value; }
}

public Chicken Chicken
{
get { return _chicken; }
set { _chicken = value; }
}

public Drink Drink
{
get { return _drink; }
set { _drink = value; }
}

public void Eat()
{
_burger.GainB();
_chicken.GainC();
_drink.GainD();

Console.WriteLine("FastFood is yummy...");
}
}

运行效果:

 

 

posted @ 2015-11-07 10:17  鬼峡  阅读(205)  评论(1编辑  收藏  举报