Builder 生成器模式或者建造者模式,个人感觉有组装的意思,组建者、组装器。
故事:
为了生产一批鞋子,由于鞋子太过复杂,通常是一部分一部分的生产,然后组装。即先生产好鞋身和鞋带,然后将鞋身和鞋带组装一起。
建模:
鞋子,包括鞋身和鞋带。
鞋子组装器:能够生产鞋身部分,生产鞋带部分,并组装。
控制中心:能够控制鞋子组装器,生产鞋身和鞋带的顺序。鞋子从这儿出货。
你是客户,想要生产一双鞋子。
类图:
实现:
Director
namespace Builder { public static class Director { public static Shoes Construct() { ShoesBuilder builder = new ShoesBuilder(); // -- 先生产鞋身,在生产鞋带 builder.BuildPart(1); builder.BuildPart(2); // -- 组装整体 builder.BuildAll(); return builder.getShoes(); } } }
Builder
namespace Builder { public abstract class Builder { public abstract void BuildPart(int partID); public abstract Builder BuildAll(); } }
ShoesBuilder
namespace Builder { public class ShoesBuilder:Builder { private Shoes shoes; public ShoesBuilder() { this.shoes = new Shoes(); } public override void BuildPart(int partID) { if (partID == 1) this.shoes.shoesBody = new ShoesBody(); else if (partID == 2) this.shoes.shoeString = new ShoeString(); } public override Builder BuildAll() { if (shoes.shoeString != null & shoes.shoesBody != null) Console.WriteLine("组装完成"); return this; } public Shoes getShoes() { Console.WriteLine("鞋子生产完成"); return this.shoes; } } }
Shoes
namespace Builder { public class Shoes { public ShoesBody shoesBody; public ShoeString shoeString; //public Shoes() //{ // Console.WriteLine("即将生产鞋子"); //} } }
ShoesBody
namespace Builder { public class ShoesBody { public ShoesBody() { Console.WriteLine("生产鞋身"); } } }
ShoeString
namespace Builder { public class ShoeString { public ShoeString() { Console.WriteLine("生产鞋带"); } } }
Program
namespace Builder { class Program { static void Main(string[] args) { Console.WriteLine("\n--生产一个复杂的产品:鞋子--\n"); Shoes shoes = Director.Construct(); } } }
效果: