Change Value to Reference(将值对象改为引用对象)

20.Change Value to Reference(将值对象改为引用对象) - 图1

做法

  • 使用Replace Constructor with Factory Method

  • 编译,测试

  • 决定由什么对象负责数据访问刷新对象的途径

    可能是一个静态字典或一个注册表对象

你也可以使用多个对象作为新对象的访问点

  • 决定这些引用对象应该预先创建好,或是应该动态创建

    如果这些引用对象是预先创建好的,而你必须从内存中将它们读取出来,那么就得确保它们在被需要的时候能够被及时加载

  • 修改工厂函数,令它返回引用对象

    如果对象是预先创建好的,你就需要考虑:万一有人索求一个其实并不存在的对象,要如何处理错误?

你可能希望对工厂函数使用Rename Method,使其传达这样的信息:它返回的是一个既存对象

  • 编译,测试

范例

  1. class Customer{
  2. public Customer(String name){
  3. _name = name;
  4. }
  5. public String getName(){
  6. return _name;
  7. }
  8. private final String _name;
  9. }
  10. class Order...
  11. public Order(String customerName){
  12. _customer = new Customer(customerName);
  13. }
  14. public String getCustomerName(){
  15. return _customer.getName();
  16. }
  17. public void setCustomer(String customerName){
  18. _customer = new Customer(customerName);
  19. }
  20. private Customer _customer;
  21. }
  22. private static int numberOfOrderFor(Collection orders,String customer){
  23. int result = 0;
  24. Iterator iter = orders.iterator();
  25. while (iter.hasNext()){
  26. Order each = (Order) iter.next();
  27. if (each.getCustomerName().equals(customer)){
  28. result ++;
  29. }
  30. }
  31. return result;
  32. }

修改后:

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;
}