步步为营.NET代码重构学习笔记十四
一、Form Templlate Method(塑造模板函数)
动机(Motivation)
有一些subclasses,其中相应的某些函数以相同顺序执行类似的措施,但各措施实际上有所不同。将各个措施分别放进独立函数中,并保持它们都有相同的签名式(signature),于是原函数也就变得相同了。然后将原函数上移至baseclass。
示例
view sourceprint?01 public abstract class Site
02 {
03 private double _unit;
04 private double _rate;
05 private double _taxRate;
06
07 public double TaxRate
08 {
09 get { return _taxRate; }
10 set { _taxRate = value; }
11 }
12
13 public double Unit
14 {
15 get { return _unit; }
16 set { _unit = value; }
17 }
18
19 public double Rate
20 {
21 get { return _rate; }
22 set { _rate = value; }
23 }
24 }
25
26 public class ResidentialSite : Site
27 {
28 public double GetBillableAmount()
29 {
30 double baseAmount = Unit * Rate;
31 double tax = baseAmount * TaxRate;
32 return basePrice + tax;
33 }
34 }
35
36 public class LifeLineSite : Site
37 {
38 public double GetBillableAmount()
39 {
40 double baseAmount = Unit * Rate*0.5;
41 double tax = baseAmount * TaxRate*0.2;
42 return basePrice + tax;
43 }
44 }
改为
view sourceprint?01 public abstract class Site
02 {
03 private double _unit;
04 private double _rate;
05 private double _taxRate;
06
07 public double TaxRate
08 {
09 get { return _taxRate; }
10 set { _taxRate = value; }
11 }
12
13 public double Unit
14 {
15 get { return _unit; }
16 set { _unit = value; }
17 }
18
19 public double Rate
20 {
21 get { return _rate; }
22 set { _rate = value; }
23 }
24 public abstract double GetBaseAmount();
25 public abstract double GetTaxAmount();
26 public double GetBillAbleAmount()
27 {
28 return GetBaseAmount() + GetTaxAmount();
29 }
30
31 }
32
33 public class ResidentialSite : Site
34 {
35 public override double GetBaseAmount()
36 {
37 return Unit * Rate;
38 }
39
40 public override double GetTaxAmount()
41 {
42 return baseAmount * TaxRate; ;
43 }
44 }
45
46 public class LifeLineSite : Site
47 {
48 public override double GetBaseAmount()
49 {
50 return Unit * Rate * 0.5;
51 }
52
53 public override double GetTaxAmount()
54 {
55 return baseAmount * TaxRate * 0.2;
56 }
57 }
二、Replace Inheritance with Delegation(以委托取代继承)
动机(Motivation)
某个subclass只使用superclass接口中的一部分,或是根本不需要继承而来的数据。在subclass中新建一个值域用以保存superclass;调整subclass函数,令它改而委托superclass;然后去掉两者之间的继承关系。
示例
view sourceprint?01 public class Vector
02 {
03 public int Size()
04 {
05 return 100;
06 }
07
08 public bool IsEmpte()
09 {
10 return false;
11 }
12 }
13
14 public class MyStack : Vector
15 {
16
17 }
改为
view sourceprint?01 public class Vector
02 {
03 public int Size()
04 {
05 return 100;
06 }
07
08 public bool IsEmpty()
09 {
10 return false;
11 }
12 }
13
14 public class MyStack
15 {
16 private Vector _vector;
17
18 public int Size()
19 {
20 return _vector
补充:Web开发 , ASP.Net ,