Change Value to Reference(将值对象改为引用对象)
做法
使用Replace Constructor with Factory Method
编译,测试
决定由什么对象负责数据访问刷新对象的途径
可能是一个静态字典或一个注册表对象
你也可以使用多个对象作为新对象的访问点
- 决定这些引用对象应该预先创建好,或是应该动态创建
如果这些引用对象是预先创建好的,而你必须从内存中将它们读取出来,那么就得确保它们在被需要的时候能够被及时加载
- 修改工厂函数,令它返回引用对象
如果对象是预先创建好的,你就需要考虑:万一有人索求一个其实并不存在的对象,要如何处理错误?
你可能希望对工厂函数使用Rename Method,使其传达这样的信息:它返回的是一个既存对象
- 编译,测试
范例
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 String getCustomerName(){
return _customer.getName();
}
public void setCustomer(String customerName){
_customer = new Customer(customerName);
}
private Customer _customer;
}
private static int numberOfOrderFor(Collection orders,String customer){
int result = 0;
Iterator iter = orders.iterator();
while (iter.hasNext()){
Order each = (Order) iter.next();
if (each.getCustomerName().equals(customer)){
result ++;
}
}
return result;
}
修改后:
class Customer{
public static Customer getNamed(String name){
return (Customer) _instances.get(name);
}
private static Dictionary _instances = New Hashtable();
static void loadCustomers(){
new Customer("lemon Car Hire").store();
new Customer("Associated Coddee Machines").store();
new Customer("Bilston Gasworks").store();
}
private void store(){
_instances.put(this.getName(), this);
}
private Customer(String name){
_name = name;
}
public String getName(){
return _name;
}
private final String _name;
}
class Order...
public Order(String customerName){
_customer = Customer.create(customerName);
}
public String getCustomerName(){
return _customer.getName();
}
public void setCustomer(String customerName){
_customer = new Customer(customerName);
}
private Customer _customer;
}