建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建构成可以创建不同的表示。即将建造代码宇表示代码分离
以构建产品为例:
产品类(Product)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace Builder_Pattern.CLASS { class Product { List<string> parts = new List<string>(); public void Add(string part) { parts.Add(part); } public void Show() { Console.WriteLine("创建产品----------"); foreach (string part in parts) { Console.WriteLine(part); } } } }
抽象建造类(Builder)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace Builder_Pattern.CLASS { abstract class Builder { public abstract void BuildPartA(); public abstract void BuildPartB(); public abstract Product GetREsult(); } }
具体建造类1(ConCreateBuilder1):继承于抽象建造类(Builder)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace Builder_Pattern.CLASS { class ConCreateBuilder1:Builder { private Product product = new Product(); public override void BuildPartA() { product.Add("部件A"); } public override void BuildPartB() { product.Add("部件B"); } public override Product GetREsult() { return product; } } }
具体建造类2(ConCreateBuilder1):继承于抽象建造类(Builder)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace Builder_Pattern.CLASS { class ConCreateBuilder2:Builder { public Product product = new Product(); public override void BuildPartA() { product.Add("部件X"); } public override void BuildPartB() { product.Add("部件Y"); } public override Product GetREsult() { return product; } } }
指挥者类(Director)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace Builder_Pattern.CLASS { class Director { public void ConCreateBuild(Builder builder) { builder.BuildPartA(); builder.BuildPartB(); } } }
测试类(TestMain)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace Builder_Pattern { class TestMain { static void Main(string[] args) { Director dir = new Director(); Builder b1 = new ConCreateBuilder1(); Builder b2 = new ConCreateBuilder2(); dir.ConCreateBuild(b1); Product product = b1.GetREsult(); product.Show(); dir.ConCreateBuild(b2); Product product1 = b2.GetREsult(); product1.Show(); Console.ReadLine(); } } }
测试结果