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

M_K抽象工厂模式

时间:2015-11-07 10:48:43      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

相关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...");
}
}

运行效果:

技术分享 

 

M_K抽象工厂模式

标签:

原文地址:http://www.cnblogs.com/Elix-kakulo/p/4944627.html

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