建造者模式

一、建造者模式适用于构建一些内部工作流程一致,实现方式不同的对象。比如说我们每个人每天基本上是用餐四次(早、中、晚和宵夜,但也有不同的)。

这里我们不考虑特殊的情况,来说明建造者模式的构建。

View Code
/// <summary>
/// 定义了每天必须完成项目的抽象接口
/// </summary>
public interface IBuild
{
void BuildMorning();

void BuildNoon();

void BuildEvening();

void BuildNight();
}
View Code
/// <summary>
/// 方案实施者
/// </summary>
public class Director
{
private IBuild _build;

public Director(IBuild build) {
this._build = build;
}

public void Build() {
this._build.BuildMorning();
this._build.BuildNoon();
this._build.BuildEvening();
this._build.BuildNight();
}
}
View Code
/// <summary>
/// 方案A
/// </summary>
public class ProjectA:IBuild
{

#region IBuild 成员

public void BuildMorning()
{
Console.WriteLine(
"早餐:包子");
}

public void BuildNoon()
{
Console.WriteLine(
"午餐:辣椒炒肉");
}

public void BuildEvening()
{
Console.WriteLine(
"晚餐:红烧豆腐");
}

public void BuildNight()
{
Console.WriteLine(
"宵夜:无");
}

#endregion
}
View Code
/// <summary>
/// 方案B
/// </summary>
public class ProjectB:IBuild
{
#region IBuild 成员

public void BuildMorning()
{
Console.WriteLine(
"早餐:汤粉");
}

public void BuildNoon()
{
Console.WriteLine(
"午餐:辣椒炒肉");
}

public void BuildEvening()
{
Console.WriteLine(
"晚餐:西红柿炒蛋");
}

public void BuildNight()
{
Console.WriteLine(
"宵夜:包子");
}

#endregion
}
View Code
/// <summary>
/// 客户端调用
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
IBuild buildA
= new ProjectA();
IBuild buildB
= new ProjectB();

Director direct
= new Director(buildA);
direct.Build();

direct
= new Director(buildB);
direct.Build();

Console.ReadKey();
}
posted @ 2011-04-26 16:30  CNF  阅读(238)  评论(0编辑  收藏  举报