Skip to content

Intent

单个类,用于存储对象并提供对它们的全局访问点. 与 Multiton 模式类似,唯一的区别是在注册表中对对象的数量没有限制.

Explanation

通俗地说

Registry 是众所周知的对象,其他对象可以使用它来查找公共对象和服务.

Programmatic Example Below is a Customer Class

java
public class Customer {

  private final String id;
  private final String name;

  public Customer(String id, String name) {
    this.id = id;
    this.name = name;
  }

  public String getId() {
    return id;
  }

  public String getName() {
    return name;
  }

}

This registry of the Customer objects is CustomerRegistry

java
public final class CustomerRegistry {

  private static final CustomerRegistry instance = new CustomerRegistry();

  public static CustomerRegistry getInstance() {
    return instance;
  }

  private final Map<String, Customer> customerMap;

  private CustomerRegistry() {
    customerMap = new ConcurrentHashMap<>();
  }

  public Customer addCustomer(Customer customer) {
    return customerMap.put(customer.getId(), customer);
  }

  public Customer getCustomer(String id) {
    return customerMap.get(id);
  }

}

Class diagram

Registry

Applicability

Use Registry pattern when

  • 客户端想要引用某个对象,客户端可以在对象的注册表中查找该对象.

Consequences

添加到注册表的大量大对象将导致大量内存消耗,因为注册表中的对象不会被垃圾回收.

Credits