《大话设计模式》学习笔记9:建造者模式

  

  《大话设计模式》学习笔记9:建造者模式

建造小人示例:

  《大话设计模式》学习笔记9:建造者模式

1.Builder:

    public abstract class PersonBuilder

    {

        public abstract void BuildHead();

        public abstract void BuildBody();

        public abstract void BuildArm();

        public abstract void BuildLeg();

    }

2.ConcreteBuilder:

    public class ThinPersonBuilder:PersonBuilder

    {

        public override void BuildHead()

        {

            Console.WriteLine("瘦头");

        }



        public override void BuildBody()

        {

            Console.WriteLine("瘦身体");

        }



        public override void BuildArm()

        {

            Console.WriteLine("瘦手");

        }



        public override void BuildLeg()

        {

            Console.WriteLine("瘦腿");

        }

    }



    public class FatPersonBuilder:PersonBuilder

    {

        public override void BuildHead()

        {

            Console.WriteLine("胖头");

        }



        public override void BuildBody()

        {

            Console.WriteLine("胖身体");

        }



        public override void BuildArm()

        {

            Console.WriteLine("胖手");

        }



        public override void BuildLeg()

        {

            Console.WriteLine("胖腿");

        }

    }

3.Director:

    public class PersonDirector

    {

        private PersonBuilder personBuilder;

        public PersonDirector(PersonBuilder personBuilder)

        {

            this.personBuilder=personBuilder;

        }

        public void CreatePerson()

        {

            personBuilder.BuildHead();

            personBuilder.BuildBody();

            personBuilder.BuildArm();

            personBuilder.BuildLeg();

        }

    }

4.客户端代码:

    class Program

    {

        static void Main(string[] args)

        {

            PersonBuilder thinPersonBuilder = new ThinPersonBuilder();

            PersonDirector thinPersonDirector = new PersonDirector(thinPersonBuilder);

            thinPersonDirector.CreatePerson();



            PersonBuilder fatPersonBuilder = new FatPersonBuilder();

            PersonDirector fatPersonDirector = new PersonDirector(fatPersonBuilder);

            fatPersonDirector.CreatePerson();

        }

    }

  建造者模式的好处是使得建造代码与表示代码分离,由于建造者隐藏了该产品是如何组装的,所欲若需要改变一个产品的内部表示,只需要再定义一个具体的建造者就可以了。

 

你可能感兴趣的:(建造者模式)