Key point: director----builder----concrete builder
UML图如下:
所需class如下:
具体代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace M_K2
{
class Program
{
static void Main(string[] args)
{
KFCSetMeal KFC = new KFCSetMeal(); //client
SetMealDirector KFCDirector = new SetMealDirector(KFC);
Console.WriteLine("Our team name is KFC...");
KFCDirector.CreateSetMeal();
MCDSetMeal MCD = new MCDSetMeal();
SetMealDirector MCDDirector = new SetMealDirector(MCD);
Console.WriteLine("Our team name is MCD...");
MCDDirector.CreateSetMeal();
}
}
}
abstract class SetMeal //builder
{
public abstract void AddBurger();
public abstract void AddChips();
public abstract void AddDrink();
}
class SetMealDirector //director
{
private SetMeal _builder;
public SetMealDirector(SetMeal builder)
{
_builder = builder;
}
public void CreateSetMeal()
{
_builder.AddBurger();
_builder.AddChips();
_builder.AddDrink();
}
}
class KFCSetMeal : SetMeal //ConcreteBuilder
{
public KFCSetMeal() : base(){}
public override void AddBurger()
{
Console.WriteLine("I am Burger from KFC...");
}
public override void AddChips()
{
Console.WriteLine("I am Chips from KFC...");
}
public override void AddDrink()
{
Console.WriteLine("I am Drink from KFC...");
}
}
class MCDSetMeal : SetMeal //ConcreteBuilder
{
public MCDSetMeal() : base() {}
public override void AddBurger()
{
Console.WriteLine("I am Burger from MCD...");
}
public override void AddChips()
{
Console.WriteLine("I am Chips from MCD...");
}
public override void AddDrink()
{
Console.WriteLine("I am Drink from MCD...");
}
}
运行结果如下:
应用: 将一个复杂对象的构建与它的表示分离,使同样的构建过程可以创建不同的表示