创建胖子和瘦子实例
1.创建人的抽象类
public abstract class PersonBuilder { public abstract void BuildHead(); public abstract void BuildBody(); public abstract void BuildLeftArm(); public abstract void BuildRightArm(); public abstract void BuildLeftLeg(); public abstract void BuildRightLeg(); }
2.封装创建人的类
public class PersonDirector { private PersonBuilder _personbuilder = null; public PersonDirector() { } public PersonDirector(PersonBuilder personbuilder) { if (_personbuilder == null) _personbuilder = personbuilder; } public void CreatePerson() { _personbuilder.BuildHead(); _personbuilder.BuildBody(); _personbuilder.BuildLeftArm(); _personbuilder.BuildRightArm(); _personbuilder.BuildLeftLeg(); _personbuilder.BuildRightLeg(); } }
3.创建瘦子
public class ThinPerson : PersonBuilder { public override void BuildBody() { Console.WriteLine("创建瘦身体"); } public override void BuildHead() { Console.WriteLine("创建瘦脑袋"); } public override void BuildLeftArm() { Console.WriteLine("创建瘦左胳膊"); } public override void BuildLeftLeg() { Console.WriteLine("创建瘦左腿"); } public override void BuildRightArm() { Console.WriteLine("创建瘦右胳膊"); } public override void BuildRightLeg() { Console.WriteLine("创建瘦右腿"); } }
4.创建胖子
public class FatPerson : PersonBuilder { public override void BuildBody() { Console.WriteLine("创建胖身体"); } public override void BuildHead() { Console.WriteLine("创建胖脑袋"); } public override void BuildLeftArm() { Console.WriteLine("创建胖左胳膊"); } public override void BuildLeftLeg() { Console.WriteLine("创建胖左腿"); } public override void BuildRightArm() { Console.WriteLine("创建胖右胳膊"); } public override void BuildRightLeg() { Console.WriteLine("创建胖右腿"); } }
5.调用实例
PersonBuilder pbt = new ThinPerson(); PersonDirector pd = new PersonDirector(pbt); pd.CreatePerson(); Console.WriteLine("-----------------------"); PersonBuilder pbf = new FatPerson(); PersonDirector pd1 = new PersonDirector(pbf); pd1.CreatePerson();