重构读书笔记-8_3-Change_Value_to_Refer
2019-06-24 本文已影响0人
MR_Model
重构第八章
3.Change Value to Reference(将实值对象改为引用对象)
你有一个class,衍生出许多相等实体,你希望将他们替换为单一对象。将这个value object(实值对象)变成一个reference object(引用对象)
Example:
class Customer {
public Customer(string name) {
_name = name;
}
public string getName() {
return _name;
}
private:
final string _name;
}
class Order...
public Order (string customerName) {
_customer = new Customer(customerName);
}
public void setCustomer(string customerName) {
_customer = new Customer(customerName);
}
public string getCustomerName() {
return _customer.getName();
}
private:
Customer _customer;
Analyse:
以上代码中,每一个Order class 实例的诞生都需要包含一个新的customer对象的创建。现实生活中是,可能一个客户拥有多份不同的订单,即多个Order共享同一个Customer对象
End:
class Order {
public Order (string customer) {
_customer = Customer.create(customer);
}
}
class Customer {
public static Customer getNamed(string name) {
return (Customer) _instances.get(name);
}
private Customer(string name) {
_name = name;
}
private static Dictionary _instances= new Hashtable();
static void loadCustomers() {
new Customer ("Lemon Car Hire").store();
new Customer ("Associated Coffee Machines").store();
new Customer ("Bilston Gasworks").store();
}
private void store() {
_instances.put(this.getName(),this);
}
}
Conclusion:
重构后的代码,使用 _instances存储name和Customer之间的关系。然后后通过loadCustomers()将对应关系存储在_instances中;通过getNamed()取得_instances中对应名称的Customer类。实现了多个order类使用同一个Customer的作用。
注意
重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!