建造者模式(Builder Pattern)
建造者模式(Builder Pattern)是将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式使得建造代码与表示代码的分离,可以使客户端不必知道产品内部组成的细节,从而降低了客户端与具体产品之间的耦合度。使用多个简单的对象一步一步构建成一个复杂的对象。属于创建型模式,它提供了一种创建对象的最佳方式。
using System;
using System.Text;
namespace ConsoleApplication
{
//建造者抽象类,定义了建造者的能力
public abstract class Builder
{
public abstract void WriteCode(); //写代码
public abstract void WriteAnnotation(); //写注释
public abstract void Compile(); //编译
}
/// <summary>
/// 高级的程序员
/// </summary>
public class SeniorBuilder : Builder
{
private StringBuilder program = new StringBuilder();
public override void WriteCode()
{
program.Append("架构代码-->");
}
public override void WriteAnnotation()
{
program.Append("写注释-->");
}
public override void Compile()
{
program.Append("编译-->");
}
public string GetContent()
{
return program.Append("代码编写完成").ToString();
}
}
/// <summary>
/// 初级的程序员
/// </summary>
public class JuniorBuilder : Builder
{
private StringBuilder program = new StringBuilder();
public override void WriteCode()
{
program.Append("实现功能代码-->");
}
public override void WriteAnnotation()
{
program.Append("写注释-->");
}
public override void Compile()
{
program.Append("编译代码-->");
}
public string GetContent()
{
return program.Append("简单小程序写完").ToString();
}
}
//监工类,制定具体的步骤
public class Director
{
private Builder builder;
public Director(Builder builder)
{
this.builder = builder;
}
//编写程序的流程,
public void Construct()
{
builder.WriteCode(); //先写代码
builder.WriteAnnotation();//写注释
builder.Compile(); //编译程序
}
}
class Program
{
static void Main(string[] args)
{
//资深的程序员1编写程序
SeniorBuilder seniorBuilder = new SeniorBuilder();
Director director1 = new Director(seniorBuilder);
director1.Construct();
string p1 = seniorBuilder.GetContent();
Console.WriteLine(p1);
//资历较浅的程序员2编写程序
JuniorBuilder juniorBuilder = new JuniorBuilder();
Director director2 = new Director(juniorBuilder);
director2.Construct();
string p2 = juniorBuilder.GetContent();
Console.WriteLine(p2);
Console.ReadKey();
}
}
}