Prototype Design Pattern In TypeScript (Part 2); Applicability

Hooman Momtaheni
3 min readMar 14, 2024

--

In Part 1, we discussed about nature of the Prototype design pattern. Now lets talk about its applications and when using prototype could be the best choice.

Applicability

Use the Prototype pattern:

  1. when a system (entire application) should be independent of how its products are created, composed, and represented.

Example:

Scenario: Imagine a system that generates invoices for customers.

Code (Without Prototype DP):

Without Prototype DP

In above code changes to invoice generation or representation would impact other parts of the system relying on the Invoice class.

Code (With Prototype DP):

Using Prototype DP

But in above code even if changes occur in the Invoice classes itself, the system remains independent of these changes as long as the concrete classes implementing the Invoice interface adhere to the contract.

2. when the classes to instantiate are specified at run-time, for example, by dynamic loading

  • dynamic loading” refers to the ability to load and register new classes at runtime instead of knowing them all beforehand. This means the application can adapt to different types of objects based on information available only at runtime, such as user input, configuration files, or external events.

Example: Imagine an application that needs to create different shapes (e.g., circle, square, triangle) based on user input.

Code (Without Prototype DP):

Without Prototype DP

In above code adding new shapes requires modifying the switch statement and change the class, making it less flexible and maintainable.

Code (With Prototype DP):

Using Prototype DP

3. to avoid building a class hierarchy of factories that parallels the class hierarchy of products.

Code (Without Prototype DP):

Without Prototype DP

Code (With Prototype DP):

Using Prototype DP

4. when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

Example:

Before Prototype DP (Manual Instantiation):

Before Prototype DP

After using Prototype DP:

*We omitDocumentFactory here. It is just a factory.

Now we have 2 prototypes (report and letter) and when we want a new instance just clone one and change its states.

In next Part we’ll talk about participants and consequences of prototype design pattern.

--

--

Hooman Momtaheni

Full Stack Web Application Developer | Admire foundations and structures | Helping companies have reliable web apps and motivated software development team