名称 | Builder |
结构 | ![]() |
意图 | 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。 |
适用性 |
|
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
18
namespace 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88
