Reputation: 15817
I am reading Martin Fowlers book i.e. Patterns of Enterprise applications: ftp://ftp.heanet.ie/mirrors/sourceforge/w/we/webtune/Patterns%20of%20Enterprise%20Application%20Architecture.pdf. I have come accross the Row Data Gateway pattern and specifically the Registry pattern. Here is a code snippet from page 149 of the book:
public static Person find(Long id) {
Person result = (Person) Registry.getPerson(id);
if (result != null)
return result;
PreparedStatement findStatement = null;
ResultSet rs = null;
try {
findStatement = DB.prepare(findStatementString);
findStatement.setLong(1, id.longValue());
rs = findStatement.executeQuery();
rs.next();
result = load(rs);
return result;
} catch (SQLException e) {
throw new ApplicationException(e);
} finally {
DB.cleanUp(findStatement, rs);
}
}
The code above calls the registry class, but I am not sure what the benefit of a Registry class is. I have read the chapter on Registry classes and I am still unclear. I understand that they are static methods.
Upvotes: 1
Views: 3396
Reputation: 280170
In this case, the registry is acting like a cache (or an IdentityMap
as you will soon see or might have already), where if your application already has a reference to the Person
object, it won't go get it from the Database.
From the book
When you want to find an object you usually start with another object that has an association to it, and use the association to navigate to it. Thus, if you want to find all the orders for a customer, you start with the customer object and use a method on it to get the orders. However, in some cases you won't have an appropriate object to start with.
The Registry
pattern is basically a holder for object references, so that you don't have to traverse complex object dependencies to get the last object in the chain. Example (you will never see in practice):
class Book {
public Author author;
}
class Author {
public City city;
}
class City {
public String name;
}
You don't want to have to go through Book -> Author
to get the City
object.
You use Registry
usually to keep references to global objects which is why Fowler proposes to use static
methods, but as you can read on page 409
, you should only rarely use this pattern "as a last resort"
.
Poorly contrived Registry example
class CityRegistry {
private static Map<String, City> references = new HashMap<>();
public static void registerCity(String id, City reference) {
references.put(id, reference);
}
public static City getCity(String id) {
return references.get(id);
}
}
Whenever you would create an instance of some class, you would register it in the Registry
so that the whole application has access to it (which might cause more problems than it solves).
Upvotes: 1