|
| 1 | +--- |
| 2 | +layout: pattern |
| 3 | +title: Registry |
| 4 | +folder: registry |
| 5 | +permalink: /patterns/registry/ |
| 6 | +categories: Creational |
| 7 | +tags: |
| 8 | + - Instantiation |
| 9 | +--- |
| 10 | + |
| 11 | +## Intent |
| 12 | +Stores the objects of a single class and provide a global point of access to them. |
| 13 | +Similar to Multiton pattern, only difference is that in a registry there is no restriction on the number of objects. |
| 14 | + |
| 15 | +## Explanation |
| 16 | + |
| 17 | +In Plain Words |
| 18 | + |
| 19 | +> Registry is a well-known object that other objects can use to find common objects and services. |
| 20 | +
|
| 21 | +**Programmatic Example** |
| 22 | +Below is a `Customer` Class |
| 23 | + |
| 24 | +```java |
| 25 | +public class Customer { |
| 26 | + |
| 27 | + private final String id; |
| 28 | + private final String name; |
| 29 | + |
| 30 | + public Customer(String id, String name) { |
| 31 | + this.id = id; |
| 32 | + this.name = name; |
| 33 | + } |
| 34 | + |
| 35 | + public String getId() { |
| 36 | + return id; |
| 37 | + } |
| 38 | + |
| 39 | + public String getName() { |
| 40 | + return name; |
| 41 | + } |
| 42 | + |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +This registry of the `Customer` objects is `CustomerRegistry` |
| 47 | +```java |
| 48 | +public final class CustomerRegistry { |
| 49 | + |
| 50 | + private static final CustomerRegistry instance = new CustomerRegistry(); |
| 51 | + |
| 52 | + public static CustomerRegistry getInstance() { |
| 53 | + return instance; |
| 54 | + } |
| 55 | + |
| 56 | + private final Map<String, Customer> customerMap; |
| 57 | + |
| 58 | + private CustomerRegistry() { |
| 59 | + customerMap = new ConcurrentHashMap<>(); |
| 60 | + } |
| 61 | + |
| 62 | + public Customer addCustomer(Customer customer) { |
| 63 | + return customerMap.put(customer.getId(), customer); |
| 64 | + } |
| 65 | + |
| 66 | + public Customer getCustomer(String id) { |
| 67 | + return customerMap.get(id); |
| 68 | + } |
| 69 | + |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +## Class diagram |
| 74 | + |
| 75 | + |
| 76 | +## Applicability |
| 77 | +Use Registry pattern when |
| 78 | + |
| 79 | +* client wants reference of some object, so client can lookup for that object in the object's registry. |
| 80 | + |
| 81 | +## Consequences |
| 82 | +Large number of bulky objects added to registry would result in a lot of memory consumption as objects in the registry are not garbage collected. |
| 83 | + |
| 84 | +## Credits |
| 85 | +* https://www.martinfowler.com/eaaCatalog/registry.html |
| 86 | +* https://wiki.c2.com/?RegistryPattern |
0 commit comments