Registry Pattern: The Central Warehouse

Where do you store your prototypes? Learn how the Registry Pattern provides a central store for your object templates, and how it works with the Prototype Pattern.

April 22, 20242 min read2 / 2

In the previous post, we learned how objects can clone themselves to solve inheritance issues. But if we have dozens of prototypes, where do we store them?

This is where the Registry Pattern comes in.

The Registry: A Central Store

A Registry is a central store, usually a Map<String, T>, that allows you to add and retrieve prototypes by a unique key.

Implementation

Java
public class StudentRegistry { private Map<String, Student> prototypes = new HashMap<>(); public void register(String key, Student prototype) { prototypes.put(key, prototype); } public Student get(String key) { Student proto = prototypes.get(key); if (proto == null) return null; return proto.copy(); // Return a CLONE, not the original! } }

The Initialization Ritual

Typically, a Registry is a Singleton initialized at the application's startup. You create your "templates" once and store them. For the rest of the application's life, clients just ask the registry for a copy.

Java
// At Startup registry.register("Nov-Batch-Template", new Student("Nov-Batch", "LLD-Module")); // In production code Student james = registry.get("Nov-Batch-Template"); james.setName("James"); // Only the name is set; the rest is pre-filled!

Real-World Use Cases

1. Game Development (The Bullet Problem)

In a game like PUBG, there are thousands of bullets.

  • A 7.62mm bullet always has the same Damage, Image, and Weight.
  • Instead of creating a brand new object ten thousand times, we store one base bullet in a Registry. Every time a player fires, we clone it and only update the Coordinates.

2. Template-Based Systems

In a learning platform like Scalar, every new class follows a standard template.

  1. We store a Prototype of the "Intro to OOPS" class (with assignments, pre-reads).
  2. When a new batch starts, we Clone the prototype from the Registry.
  3. We only update the batch-specific data (Instructor, Date).

Summary: The Industrial-Grade Copy

The Prototype and Registry patterns together solve the problem of creating varied objects efficiently and cleanly.

  1. The Prototype: Allows objects to clone themselves without breaking inheritance or encapsulation.
  2. The Registry: Provides a central, organized warehouse to store and retrieve these clones.

Key Takeaway

For Java developers, remember to use the Copy Constructor inside your copy() method. For JS/TS developers, use the Prototype pattern when you need a Deep Copy of complex class hierarchies.

In our next module, we will explore the Factory Pattern, where we move from copying objects to manufacturing them from scratch.