设计模式---建造者模式

在Gof的23种设计模式中对Builder Pattern的定义是:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

 

从程序角度来说,就是在基类定义某种事物创建的过程或业务流程,在子类进行重写或是使用基类方法。这样创建出来的实例不会因为过程或流程的丢失而使业务失败。举例来说,我们要建一辆汽车,汽车需要车轮、方向盘、发动机、油门、刹车等上百个设计功能和流程。现在我需要自己建一辆汽车,那么汽车需要的这上百个流程我都要自己完成,很可能由于其中某个流程忘做或是流程错误,使整车无法使用。这个时候,就需要使用建造者模式来解决这个问题了。

 

首先我们需要定义一个建造汽车的基类,里面的CreateCarInstance()方法定义了建造一辆汽车所需要的所有流程。

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TJVictor.DesignPattern.BuilderPattern { public class BuilderCar { public void CreateCarInstance() { CreateWheel(); CreateSteering(); CreateEngine(); } public virtual string CarName { get { return "汽车"; } } protected virtual void CreateWheel() { Console.WriteLine("汽车有四个轮子"); } protected virtual void CreateSteering() { Console.WriteLine("汽车有一个方向盘"); } protected virtual void CreateEngine() { Console.WriteLine("汽车有发动机"); } } }

然后我们自己定义一个汽车类,继承汽车的基类,并且重写基类里面的CreateSteering()和CreateEngine()方法。

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TJVictor.DesignPattern.BuilderPattern { public class MyCar:BuilderCar { public override string CarName { get { return "我的汽车是飞度"; } } protected override void CreateSteering() { base.CreateSteering(); } protected override void CreateEngine() { Console.WriteLine("我的发动机是本田Honda原产的"); } } }

调用代码为:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using TJVictor.DesignPattern.FactoryPattern; using TJVictor.DesignPattern.BuilderPattern; namespace TJVictor.DesignPattern { class Program { static void Main(string[] args) { #region TJVictor.DesignPattern.BuilderPattern BuilderCar myCar = new MyCar(); Show(myCar.CarName); myCar.CreateCarInstance(); #endregion #region Console.ReadLine(); Console.ReadLine(); #endregion } #region Assistant public static void Show(int number) { Console.WriteLine(number.ToString()); } public static void Show(string str) { Console.WriteLine(str); } #endregion } }

执行结果为:

 我的汽车是飞度 汽车有四个轮子 汽车有一个方向盘 我的发动机是本田Honda原产的

在MyCar类里面,我们重写了CreateEngine()方法,使自己汽车的发动机变成了本田Honda的。车轮对于汽车是必须的,但是我们在MyCar里面由于疏忽,并没有写CreateWheel()方法,但是没有关系,因为基类中已经有CreateWheel()方法了。所以对于CreateCarInstance()来说,建一辆是稳定的。

 

如需转载,请注明本文原创自CSDN TJVictor专栏:http://blog.csdn.net/tjvictor

你可能感兴趣的:(设计模式,String,Class)