建造者模式
需要创建一个复杂对象,并且这个对象由子对象通过一定步骤组合而成,这样就可以使用建造者模式
现在,我有了螺丝螺帽轮胎,我要组装车了
组装的话,我需要三个步骤:1 穿螺丝 2装轮胎 3 拧螺帽,但是我一个一个装的话太累了,那么就找人干
车辆类:
public class Car { List<string> parts = new List<string>(); public void Add(string Unit) { parts.Add(Unit); } public void GetCar() { foreach (var item in parts) { Console.WriteLine(item.ToString()); } } }
建造者类:
public abstract class Builder { public abstract void PutScrew(); public abstract void PutTire(); public abstract void PutNut(); public abstract Car GetCar(); } public class Builder1 : Builder { Car car = new Car(); public override Car GetCar() { return car; } public override void PutNut() { car.Add("装螺帽"); } public override void PutScrew() { car.Add("装螺丝"); } public override void PutTire() { car.Add("装轮胎"); } }
建造者监督类
public void BuildCar(Builder builder) { builder.PutScrew(); builder.PutNut(); builder.PutTire(); }
客户端调用:
class Program { static void Main(string[] args) { Builder builder1 = new Builder1(); Direct direct = new Direct(); direct.BuildCar(builder1); Car car=builder1.GetCar(); car.GetCar(); Console.ReadKey(); } }