建造者模式
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Builder{//果园类public class Orchard{//果园名称string name;//苹果public string Apple { get; set; }//橘子public string Orange { get; set; }//构造方法public Orchard(string name){this.name = name;Console.WriteLine(\"建造{0}果园\", name);}//果园种植方法public void Plant(){Console.WriteLine(\"{0}果园种植{1}{2}\", this.name, this.Apple, this.Orange);}}//果园建造指导者类public class OrchardDirector{//果园建造者OrchardBuilder orchardBuilder;//构造函数public OrchardDirector(OrchardBuilder orchardBuilder){this.orchardBuilder = orchardBuilder;//为果园建造者赋值}public Orchard Construct(){//创建苹果orchardBuilder.BuildApple();//创建苹果orchardBuilder.BuildOrange();//返回果园实例return orchardBuilder.GetOrchard();}}//果园抽象建造者public abstract class OrchardBuilder{public abstract void BuildApple();public abstract void BuildOrange();public abstract Orchard GetOrchard();}//北京果园建造者public class BJOrchardBuilder : OrchardBuilder{//北京果园Orchard bjOrchard = new Orchard(\"北京\");//创建北京苹果public override void BuildApple(){bjOrchard.Apple = \"北京苹果\";}//创建北京橘子public override void BuildOrange(){bjOrchard.Orange = \"北京橘子\";}//获取北京果园实例public override Orchard GetOrchard(){return bjOrchard;}}//上海果园建造者public class SHOrchardBuilder : OrchardBuilder{//上海果园Orchard shOrchard = new Orchard(\"上海\");//创建上海苹果public override void BuildApple(){shOrchard.Apple = \"上海苹果\";}//创建上海橘子public override void BuildOrange(){shOrchard.Orange = \"上海橘子\";}//获取上海果园实例public override Orchard GetOrchard(){return shOrchard;}}class Program{static void Main(string[] args){//创建北京果园建造指导者OrchardDirector bjorchardDirector = new OrchardDirector(new BJOrchardBuilder());//北京果园指导者建造北京果园Orchard bjorchard = bjorchardDirector.Construct();//北京果园种植水果bjorchard.Plant();//创建上海果园建造指导者OrchardDirector shorchardDirector = new OrchardDirector(new SHOrchardBuilder());//上海果园指导者建造北京果园Orchard shorchard = shorchardDirector.Construct();//上海果园种植水果shorchard.Plant();Console.ReadKey();}}}
代码解析
以上例代码实现了建造者模式,首先创建了果园类Orchard,该类由Apple和Orange两部分组成;然后创建抽象果园建造者类 OrchardBuilder 及其派生类 BJOrchardBuilder 和SHOrchardBuilder,这两个具体类主要实现对果园各部分的建造;最后创建了果园建造指导者类OrchardDirector,该类主要是创建Orchard类的执行者,该类中保存了OrchardBuilder对象的引用,该引用决定了OrchardDirector以何种方式来创建Orchard类。通过OrchardDirector实现了Orchard类及其创建的分离,降低了调用者对Orchard类创建的耦合性。
说明:建造者模式与工厂模式同属于类的创建型模式,但建造者模式主要用于结构比较复杂的对象的创建,对于复杂的对象可能存在多个部分需要被创建,而且存在多种创建方法,通过建造者模式可以实现对象的表现形式与其创建过程的分离。