码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-05-11 21:21:44      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

  技术分享

建造小人示例:

  技术分享

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();
        }
    }

 

  建造者模式:将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

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

 

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

标签:

原文地址:http://www.cnblogs.com/walden1024/p/4495445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!