The Registry pattern is an object well-known by all other objects in an application, used to find other shared objects and services.
It acts as a centralized address book or directory where references to global objects—such as database connections, user settings, or messaging services—are registered and retrieved.
# When to use it?
This pattern is ideal when multiple parts of an application need to access the same set of global objects or services, and you want to avoid passing references excessively through parameters.
It is useful for centralizing the management of shared objects and simplifying how different application components interact with them.
# Pros
-
verified
Centralization
Provides a single point to find common objects.
-
verified
Parameter Reduction
Avoids having to pass global object references through multiple levels of methods.
-
verified
Ease of Access
Simplifies the way objects access shared services.
# Cons
-
warning
Hidden Global State
Can hide dependencies, making it harder to understand the data flow.
-
warning
Testability Difficulty
Testing classes that depend on a global Registry can be more complex.
-
warning
Possible Abuse
Can be overused to hide poor design practices.
# Detailed Example in Java
Let's assume a Registry that stores the database connection and a configuration service:
Registry.java
public class Registry {
private static Registry instance;
private Connection dbConnection;
private ConfigService configService;
private Registry() {}
public static Registry getInstance() {
if (instance == null) {
instance = new Registry();
}
return instance;
}
public Connection getDbConnection() {
return dbConnection;
}
public void setDbConnection(Connection dbConnection) {
this.dbConnection = dbConnection;
}
public ConfigService getConfigService() {
return configService;
}
public void setConfigService(ConfigService configService) {
this.configService = configService;
}
}
# Conclusions
The Registry pattern facilitates access to global objects and services, promoting centralized organization and simplifying interaction between components. It is essential to use it with moderation and be aware of the global dependencies it introduces.