23种设计模式之建造者模式(Builder)
建造者模式强调将一个复杂对象的创建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式是一步一步地创建一个复杂的对象,它允许用户只通过制定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。建造者模式属于对象创建型模式。
public abstract class Builder
{
public abstract void MakeTitle(string title);
public abstract void MakeString(string str);
public abstract void MakeItems(string[] items);
public abstract Object GetResult();
}
public class Director
private Builder builder;
public Director(Builder builder)
this.builder = builder;
public Object Construct()
builder.MakeTitle("Greeting");
builder.MakeString("从早上到白天结束");
builder.MakeItems(new string[] { "早安", "午安" });
builder.MakeString("到了晚上");
builder.MakeItems(new string[] { "晚安", "好梦" });
return builder.GetResult();
public class TextBuilder : Builder
private StringBuilder sb = new StringBuilder();
public override void MakeTitle(string title)
sb.Append("【" + title + "】/n/n");
public override void MakeString(string str)
sb.Append(str + "/n/n");
public override void MakeItems(string[] items)
for (int i = 0; i < items.Length; i++)
sb.Append(items[i] + "/n");
sb.Append("/n");
public override object GetResult()
return sb.ToString();
class Program
static void Main(string[] args)
//生成器模式
Builder.Director director = new Builder.Director(new Builder.TextBuilder());
string result = director.Construct() as string;
Console.WriteLine(result);