步步为营 .NET 代码重构学习笔记 九
一、Duplicate Observed Data(复制[被监视数据])
动机(Motivation)
将该笔数据拷贝到一个domain object中。建立一个Observer模式,用以对domain object 和GUI object内的重复数据进行同步控制(sync)。
示例
html">步步为营 .NET 设计模式学习笔记 十二、Observer (观察者模式)
二、Change Unidirectional Association to Bidirectional(将单向关联改为双向)
动机(Motivation)
添加一个反指针,并使修改函数(modifiers)能够同时更新两条连接。
示例
public class Order
{
private Customer _customer;public Customer NewCustomer
{
get { return _customer; }
set { _customer = value; }
}
}public class Customer
{
}改为
public class Order
{
public List<Customer> CustomerList = new List<Customer>();public void AddCustomer(Customer arg)
{
arg.orderlist.Add(this);
CustomerList.Add(arg);
}public void RemoveCustomer(Customer arg)
{
arg.orderlist.Remove(this);
CustomerList.Remove(arg);
}
}public class Customer
{
public List<Order> orderlist = new List<Order>();
public void AddOrder(Order arg)
{
arg.CustomerList.Add(this);
orderlist.Add(arg);
}
public void RemoveOrder(Order arg)
{
arg.CustomerList.Remove(this);
orderlist.Remove(arg);
}
}
三、Change Bidirectional Association to Unidirectional(将双向改为单向)
动机(Motivation)
两个classes之间有双向关联,但其中一个class如今不再需要另一个class的特性。
示例
public class Order
{
public List<Customer> CustomerList = new List<Customer>();public void AddCustomer(Customer arg)
{
arg.orderlist.Add(this);
CustomerList.Add(arg);
}public void RemoveCustomer(Customer arg)
{
arg.orderlist.Remove(this);
CustomerList.Remove(arg);
}
}public class Customer
{
public List<Order> orderlist = new List<Order>();
public void AddOrder(Order arg)
{
arg.CustomerList.Add(this);
orderlist.Add(arg);
}
public void RemoveOrder(Order arg)
{
arg.CustomerList.Remove(this);
orderlist.Remove(arg);
}
}
改为
public class Order
{
private Customer _customer;public Customer NewCustomer
{
get { return _customer; }
set { _customer = value; }
}
}public class Customer
{
}
四、Replace Magic Number with Symbolic Constant(以符号常量/字面常量取侙魔法数)
动机(Motivation)
创造一个常量,根据其意义为它命名,并将上述的字面数值替换为这个常量。
示例
public double PotentialEnergy(double mass, double height)
{
return mass * 9.51 * height;
}
改为
private double GRAVITATIONAL_CONSTANT = 9.51;
public double PotentialEnergy(double mass, double height)
{
return mass * GRAVITATIONAL_CONSTANT * height;
}
五、Encapsulate Field(封装值域)
动机(Motivation)
将它声明为private,并提供相应的访问函数(accessors)
示例
public string _name;
改为
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
六、Replace Type Code with Class(以类取代型别码)
动机(Motivation)
以一个新的class替换该数值型别码(type code)
示例
public class Person
{
public int O = 0;
public int A = 1;
public int B = 2;
&n
补充:Web开发 , ASP.Net ,