Builder模式--经典模式
public class Vehicle { public IEnumerable<string> Wheels { get; set; } public IEnumerable<string> Lights { get; set; } }
/// <summary> /// abstract builder /// </summary> public abstract class VehicleBuilderBase { public Vehicle Vehicle { get; protected set; } public virtual void Create() { Vehicle = new Vehicle(); } public abstract void AddWheels(); public abstract void AddLights(); }
/// <summary> /// concrete builder /// </summary> public class CarBuilder : VehicleBuilderBase { #region VehicleBuilderBase Members public override void AddWheels() { Vehicle.Wheels = new string[] {"front", "front", "back", "back"}; } public override void AddLights() { Vehicle.Lights = new string[] { "front", "front", "back", "back" }; } #endregion } /// <summary> /// concrete builder /// </summary> public class BicycleBuilder : VehicleBuilderBase { #region VehicleBuilderBase Members public override void AddWheels() { Vehicle.Wheels = new string[] { "front", "back" }; } public override void AddLights() { Vehicle.Lights = null; } #endregion }
调用
[TestMethod] public void BuildUp() { var maker = new VehicleMaker(); maker.Builder = new CarBuilder(); maker.Construct(); Assert.AreEqual<int>(4, maker.Vehicle.Wheels.Count()); Assert.AreEqual<int>(4, maker.Vehicle.Lights.Count()); maker.Builder = new BicycleBuilder(); maker.Construct(); Assert.AreEqual<int>(2, maker.Vehicle.Wheels.Count()); Assert.IsNull(maker.Vehicle.Lights); }
posted on 2013-03-29 11:02 HOT SUMMER 阅读(157) 评论(0) 编辑 收藏 举报