Patterncore
Registry
Also called Registry pattern, well-known object, global registry.
A registry is a well-known object that other objects use to find common objects and services, such as finders, when they have no reference to start from.
- Family
- architectural
- Intent
- Give the program one well-known place to find common objects and services.
Intent
A registry is "A well-known object that other objects can use to find common objects and services."1 The program puts the objects in the registry once. Code anywhere in the program can then get them from the registry.
Problem
Usually, code finds an object through an association. To get the orders of a customer, the code starts with the customer object and asks it for its orders. But sometimes the code has no object to start from. It has only a key, such as the ID of a customer. The catalog says: "In this case you need some kind of lookup method - a finder - but the question remains: How do you get to the finder?"1
If each class must get the finder through its constructor, then each class between the start of the program and the code that needs the finder must also pass it on. This adds parameters to many classes that do not use them.
Solution
Put the common objects in one object that all the code can find. The parts are:
- The registry. It is one object, which the code gets through static methods or functions. The methods hide how the registry keeps its data.
- One explicit method for each service. A method such as
person_finder()has a clear name and a type. A lookup by a string key is more flexible, but the compiler cannot check it. - The install step. The start of the program puts the real objects in the registry. A test can install a registry with stubs.
- The scope. The registry can be the same for all the process, or there can be one registry for each thread or each session.2
main: Registry.install(Registry(person_finder=PersonFinder(...)))
code: Registry.person_finder().find(1) --> the registry --> PersonFinder
test: Registry.install(Registry(person_finder=StubFinder()))
The catalog says that "A Registry is essentially a global object, or at least it looks like one - even if it isn't as global as it may appear."1 In the following program, the logging module of Python is the registry. It gives the same logger to each caller that asks for the same name.
import logging
# The logging module keeps a registry of loggers by name.
a = logging.getLogger("shop.orders") # in one module
b = logging.getLogger("shop.orders") # in another module, with no reference to a
print("the same logger object:", a is b)
the same logger object: True
Example
Each example has a Registry with one service, a person finder. The function greet is deep in the program and has no reference to a finder, so it gets the finder from the registry. The program installs a registry with a finder that reads a table, and greets Ann and Bob. Then it installs a registry with a stub finder, as a test does. Last, it installs an empty registry, and greet gives a clear error.
class PersonFinder:
def __init__(self, rows):
self.rows = rows
def find(self, person_id):
return self.rows[person_id]
class Registry:
"""A well-known object with one explicit method for each service."""
_sole = None
def __init__(self, person_finder=None):
self._person_finder = person_finder
@classmethod
def install(cls, registry): # the start of the program, or a test, sets the registry
cls._sole = registry
@classmethod
def person_finder(cls):
if cls._sole is None or cls._sole._person_finder is None:
raise LookupError("no person finder is registered")
return cls._sole._person_finder
def greet(person_id): # code deep in the program, with no reference to a finder
print(f"hello, {Registry.person_finder().find(person_id)}")
class StubFinder:
def find(self, person_id):
return f"test person {person_id}"
Registry.install(Registry(person_finder=PersonFinder({1: "ann", 2: "bob"})))
greet(1)
greet(2)
Registry.install(Registry(person_finder=StubFinder())) # a test installs a stub
print("in a test: ", end="")
greet(1)
Registry.install(Registry())
try:
greet(1)
except LookupError as e:
print("with an empty registry:", e)
hello, ann
hello, bob
in a test: hello, test person 1
with an empty registry: no person finder is registered
- Verdict: idiom. The registry is a class with a class attribute that holds the sole instance, and class methods that the program calls. The methods hide the instance, so a test can install another one.
- Each service has its own explicit method, such as
person_finder(). This is easier to read and check than a lookup by a string key.
import java.util.Map;
public class Main {
interface PersonFinder {
String find(int personId);
}
static class TablePersonFinder implements PersonFinder {
private final Map<Integer, String> rows;
TablePersonFinder(Map<Integer, String> rows) { this.rows = rows; }
public String find(int personId) { return rows.get(personId); }
}
// A well-known object with one explicit method for each service.
static class Registry {
private static volatile Registry sole = new Registry(null);
private final PersonFinder personFinder;
Registry(PersonFinder personFinder) { this.personFinder = personFinder; }
// The start of the program, or a test, sets the registry.
static void install(Registry registry) { sole = registry; }
static PersonFinder personFinder() {
PersonFinder f = sole.personFinder;
if (f == null) throw new IllegalStateException("no person finder is registered");
return f;
}
}
// Code deep in the program, with no reference to a finder.
static String greet(int personId) { return "hello, " + Registry.personFinder().find(personId); }
public static void main(String[] args) {
Registry.install(new Registry(new TablePersonFinder(Map.of(1, "ann", 2, "bob"))));
System.out.println(greet(1));
System.out.println(greet(2));
Registry.install(new Registry(id -> "test person " + id)); // a test installs a stub
System.out.println("in a test: " + greet(1));
Registry.install(new Registry(null));
try {
System.out.println(greet(1));
} catch (IllegalStateException e) {
System.out.println("with an empty registry: " + e.getMessage());
}
}
}
hello, ann
hello, bob
in a test: hello, test person 1
with an empty registry: no person finder is registered
- Verdict: idiom. A
static volatilefield holds the sole instance, so a new instance that one thread installs is visible to other threads. The static methods are the interface of the registry. - The stub finder is a lambda, because
PersonFinderhas one abstract method.
class PersonFinder {
constructor(rows) {
this.rows = rows;
}
find(personId) {
return this.rows.get(personId);
}
}
// A well-known object with one explicit method for each service.
class Registry {
static #sole = null;
constructor({ personFinder = null } = {}) {
this.personFinder = personFinder;
}
// The start of the program, or a test, sets the registry.
static install(registry) {
Registry.#sole = registry;
}
static personFinder() {
const finder = Registry.#sole?.personFinder;
if (!finder) throw new Error("no person finder is registered");
return finder;
}
}
// Code deep in the program, with no reference to a finder.
const greet = (personId) => `hello, ${Registry.personFinder().find(personId)}`;
class StubFinder {
find(personId) {
return `test person ${personId}`;
}
}
Registry.install(new Registry({ personFinder: new PersonFinder(new Map([[1, "ann"], [2, "bob"]])) }));
console.log(greet(1));
console.log(greet(2));
Registry.install(new Registry({ personFinder: new StubFinder() })); // a test installs a stub
console.log("in a test: " + greet(1));
Registry.install(new Registry());
try {
console.log(greet(1));
} catch (e) {
console.log("with an empty registry:", e.message);
}
hello, ann
hello, bob
in a test: hello, test person 1
with an empty registry: no person finder is registered
- Verdict: idiom. A static private field holds the sole instance, and static methods give the services. A module-level variable that the module exports through functions is the same design.
- The optional chaining
?.makes an empty registry give a clear error, not aTypeError.
package main
import (
"errors"
"fmt"
"sync"
)
type PersonFinder interface {
Find(personID int) string
}
type tableFinder map[int]string
func (t tableFinder) Find(id int) string { return t[id] }
type stubFinder struct{}
func (stubFinder) Find(id int) string { return fmt.Sprintf("test person %d", id) }
// Registry is a well-known object with one explicit method for each service.
type Registry struct {
PersonFinder PersonFinder
}
var (
mu sync.RWMutex
sole Registry
)
// Install sets the registry. The start of the program, or a test, calls it.
func Install(r Registry) {
mu.Lock()
defer mu.Unlock()
sole = r
}
// Finder returns the registered person finder.
func Finder() (PersonFinder, error) {
mu.RLock()
defer mu.RUnlock()
if sole.PersonFinder == nil {
return nil, errors.New("no person finder is registered")
}
return sole.PersonFinder, nil
}
// greet is code deep in the program, with no reference to a finder.
func greet(id int) (string, error) {
f, err := Finder()
if err != nil {
return "", err
}
return "hello, " + f.Find(id), nil
}
func main() {
Install(Registry{PersonFinder: tableFinder{1: "ann", 2: "bob"}})
for _, id := range []int{1, 2} {
s, _ := greet(id)
fmt.Println(s)
}
Install(Registry{PersonFinder: stubFinder{}}) // a test installs a stub
s, _ := greet(1)
fmt.Println("in a test: " + s)
Install(Registry{})
if _, err := greet(1); err != nil {
fmt.Println("with an empty registry:", err)
}
}
hello, ann
hello, bob
in a test: hello, test person 1
with an empty registry: no person finder is registered
- Verdict: idiom. A package-level variable holds the registry, and a
sync.RWMutexprotects it, because goroutines can read it while a test installs another one. Finderreturns an error and not a nil interface, so the caller must handle an empty registry.
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
trait PersonFinder: Send + Sync {
fn find(&self, person_id: u32) -> String;
}
struct TableFinder(HashMap<u32, String>);
impl PersonFinder for TableFinder {
fn find(&self, id: u32) -> String {
self.0.get(&id).cloned().unwrap_or_default()
}
}
struct StubFinder;
impl PersonFinder for StubFinder {
fn find(&self, id: u32) -> String {
format!("test person {}", id)
}
}
// A well-known object with one explicit method for each service.
#[derive(Default)]
struct Registry {
person_finder: Option<Arc<dyn PersonFinder>>,
}
static SOLE: RwLock<Registry> = RwLock::new(Registry { person_finder: None });
// The start of the program, or a test, sets the registry.
fn install(registry: Registry) {
*SOLE.write().unwrap() = registry;
}
fn person_finder() -> Result<Arc<dyn PersonFinder>, &'static str> {
SOLE.read().unwrap().person_finder.clone().ok_or("no person finder is registered")
}
// Code deep in the program, with no reference to a finder.
fn greet(id: u32) -> Result<String, &'static str> {
Ok(format!("hello, {}", person_finder()?.find(id)))
}
fn main() {
let rows = HashMap::from([(1, "ann".to_string()), (2, "bob".to_string())]);
install(Registry { person_finder: Some(Arc::new(TableFinder(rows))) });
println!("{}", greet(1).unwrap());
println!("{}", greet(2).unwrap());
install(Registry { person_finder: Some(Arc::new(StubFinder)) }); // a test installs a stub
println!("in a test: {}", greet(1).unwrap());
install(Registry::default());
if let Err(e) = greet(1) {
println!("with an empty registry: {}", e);
}
}
hello, ann
hello, bob
in a test: hello, test person 1
with an empty registry: no person finder is registered
- Verdict: idiom. A
staticRwLockholds the registry. Rust does not allow a mutable global without a lock orunsafe, so the shared state is explicit in the type. Arc<dyn PersonFinder>lets a caller keep the finder after the read lock is released.
Consequences
Benefits.
- Fewer parameters. Code that needs a finder or a service gets it from the registry, and the classes between do not pass it on.
- One place to configure. The start of the program installs all the common objects in one place.
- Replaceable objects. Because the code calls the methods of the registry and not a concrete class, a test can install a Test double.
Liabilities.
A registry is global state, and a test that changes it can break other tests. In the following program, a test installs a stub in the registry and does not restore the real finder. The code that runs after the test uses the stub.
This code runs but gives a wrong answer on purpose.
class Registry:
person_finder = None # global state
Registry.person_finder = lambda person_id: {1: "ann"}[person_id]
def test_greeting():
Registry.person_finder = lambda person_id: f"test person {person_id}"
assert Registry.person_finder(1) == "test person 1" # the test does not restore the registry
test_greeting()
print("after the test, the program greets: hello,", Registry.person_finder(1))
after the test, the program greets: hello, test person 1
Let each test install a registry and restore the previous one when it ends, for example in a fixture or a finally block. Or give the object to the code as a parameter.
Hidden dependencies. The signature of a class does not show that the class uses the registry. To know what a class needs, you must read its code.
Shared state between threads. If threads read the registry while one thread changes it, the registry needs a lock, or each thread needs its own registry.
When not to use it
When the code can get the object as a parameter. If the caller has the object, or a reference to an object that has it, pass it. A parameter shows the dependency and needs no global state.
When a framework already does dependency injection. The framework gives each class what its constructor asks for. A registry next to it adds a second way to get the same object.
Variants and related patterns
Process scope and thread scope. A registry for the process holds objects that all threads share, such as a finder. A registry for each thread holds objects that belong to one request or one transaction, such as the Identity Map of a Unit of Work.
Singleton. A registry is often a Singleton pattern. But the static methods of the registry hide the instance, so the program or a test can replace it. A plain singleton class often cannot be replaced.
Service locator. A Service locator is a registry of services. Dependency injection is the alternative: the code gets the objects that it needs, and does not ask for them.
Separated interface. The registry can give the code a Separated interface, so the code does not depend on the implementation that the program installs.
Known uses
- In the Python logging module, "Multiple calls to getLogger() with the same name will always return a reference to the same Logger object."3 The module keeps the loggers by name, and the documentation says that loggers "should NEVER be instantiated directly".3
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Registry, pattern summary
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Registry
- Python documentation, logging, Logging facility for Python, Logger Objects
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 7RR5MZ Edit this page History Report an error Markdown