设计模式之美:Role Object(角色对象)(二)
ecoratedCore = core;
67 }
68
69 public override CustomerRole GetRole(string spec)
70 {
71 return _decoratedCore.GetRole(spec);
72 }
73
74 public override void AddRole(string spec)
75 {
76 _decoratedCore.AddRole(spec);
77 }
78
79 public override void RemoveRole(string spec)
80 {
81 _decoratedCore.RemoveRole(spec);
82 }
83
84 public override bool HasRole(string spec)
85 {
86 return _decoratedCore.HasRole(spec);
87 }
88
89 public override void SomeCommonOperation1()
90 {
91 _decoratedCore.SomeCommonOperation1();
92 }
93 }
94
95 public class Borrower : CustomerRole
96 {
97 public Borrower(CustomerCore core)
98 : base(core)
99 {
100 }
101
102 public void SomeOperationForBorrower()
103 {
104 // do something for borrower
105 }
106 }
107
108 public class Investor : CustomerRole
109 {
110 public Investor(CustomerCore core)
111 : base(core)
112 {
113 }
114
115 public void SomeOperationForInvestor()
116 {
117 // do something for investor
118 }
119 }
120
121 public class CustomerRoleFactory
122 {
123 public CustomerRole CreateRole(string spec, CustomerCore core)
124 {
125 CustomerRole newRole = null;
126
127 if (spec == "Borrower")
128 {
129 newRole = new Borrower(core);
130 }
131 else if (spec == "Investor")
132 {
133 newRole = new Investor(core);
134 }
135
136 return newRole;
137 }
138 }
139
140 public class Client
141 {
142 public void TestCase1()
143 {
144 Customer customer = new CustomerCore(new CustomerRoleFactory());
145 customer.AddRole("Borrower");
146 customer.AddRole("Investor");
147
148 CustomerRole customerRole1 = customer.GetRole("Borrower");
149 Borrower borrower = (Borrower)customerRole1;
150 borrower.SomeCommonOperation1();
151 borrower.SomeOperationForBorrower();
152
153 CustomerRole customerRole2 = customer.GetRole("Investor");
154 Investor investor = (Investor)customerRole2;
155 investor.SomeCommonOperation1();
156 investor.SomeOperationForInvestor();
157 }
158 }
159 }