建筑模式


名称 Builder
结构
意图 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
适用性
  • 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
  • 当构造过程必须允许被构造的对象有不同的表示时。
example
 1// Builder
 2
 3// Intent: "Separate the construction of a complex object from its
 4// representation so that the same construction process can create
 5// different representations". 
 6
 7// For further information, read "Design Patterns", p97, Gamma et al.,
 8// Addison-Wesley, ISBN:0-201-63361-2
 9
10/* Notes:
11 * Builder is an object creational design pattern that codifies the 
12 * construction process outside of the actual steps that carries out 
13 * the construction - thus allowing the construction process itself
14 * to be reused. 
15 * 
16 */

17 
18namespace Builder_DesignPattern
19{
20    using System;
21
22    // These two classes could be part of a framework,
23    // which we will call DP
24    // ===============================================
25    
26    class Director 
27    {
28        public void Construct(AbstractBuilder abstractBuilder)
29        {
30            abstractBuilder.BuildPartA();
31            if (1==1 ) //represents some local decision inside director
32            {
33                abstractBuilder.BuildPartB();            
34            }

35            abstractBuilder.BuildPartC();            
36        }

37
38    }

39
40    abstract class AbstractBuilder 
41    {
42        abstract public void BuildPartA();
43        abstract public void BuildPartB();
44        abstract public void BuildPartC();
45    }

46
47    // These two classes could be part of an application 
48    // =================================================
49
50    class ConcreteBuilder : AbstractBuilder 
51    {
52        override public void BuildPartA()
53        {
54            // Create some object here known to ConcreteBuilder
55            Console.WriteLine("ConcreteBuilder.BuildPartA called");
56        }

57                
58        override public void BuildPartB()
59        {
60            // Create some object here known to ConcreteBuilder
61            Console.WriteLine("ConcreteBuilder.BuildPartB called");
62        }

63        
64        override public void BuildPartC()
65        {
66            // Create some object here known to ConcreteBuilder
67            Console.WriteLine("ConcreteBuilder.BuildPartC called");
68        }

69    }
    
70
71    /// <summary>
72    ///    Summary description for Client.
73    /// </summary>

74    public class Client
75    {
76        public static int Main(string[] args)
77        {
78            ConcreteBuilder concreteBuilder = new ConcreteBuilder();
79            Director director = new Director();
80
81            director.Construct(concreteBuilder);
82
83            return 0;
84        }

85    }

86}

87
88

posted @ 2005-06-24 08:19  DarkAngel  阅读(895)  评论(0编辑  收藏  举报