DEV Community

Cover image for Learn Design Patterns: Unlocking the Power of the Prototype Design Pattern
Sami Maachi
Sami Maachi

Posted on

Learn Design Patterns: Unlocking the Power of the Prototype Design Pattern

Design patterns are crucial in writing clean, efficient, and maintainable software. Today, we’re exploring the Prototyping Design Pattern, a creational pattern that simplifies the process of creating new objects by cloning existing ones.

This article will explore the fundamentals of the Prototype Pattern, its use cases, and its practical applications.

Table of Contents

  1. Prototype Pattern Definition

  2. Scenario: Understanding the Problem

  3. Real-Life Projects That Use the Prototype Pattern

Prototype Pattern Definition

The Prototype Design Pattern is a creational pattern that allows you to create new objects by copying or cloning existing objects rather than instantiating them directly.

This pattern is useful when:

  • Object creation is costly/resource-intensive.

  • Object configurations are complex, and setting them up repeatedly is inefficient.

  • The goal is to maintain consistent object structures while allowing slight variations.

TLDR, the Prototype Pattern helps you create objects quickly and efficiently by reusing an existing instance as a template.

Scenario: Understanding the Problem

Imagine you’re managing a game where every character has unique attributes and abilities, like speed, strength, and weapons.

Now, you want to introduce a feature that allows players to clone their characters with slight variations, like different armor or enhanced abilities, without needing to recreate the entire character from scratch.

Without the Prototype Pattern, you might have to write repetitive code for creating new instances and manually copying all the properties, leading to unnecessary complexity and potential errors.

With the Prototype Pattern, you can simply clone an existing character and tweak only the required attributes, ensuring a seamless and efficient process.

This pattern allows you to:

  • Avoid redundant initialization code.

  • Ensure the consistency of complex objects.

  • Customize new instances effortlessly.

Implementation of the Prototype Design Pattern in TypeScript

Here’s a step-by-step implementation of the Prototype Design Pattern in TypeScript. We’ll use a game character example to illustrate how cloning works and why it’s beneficial.

Step 1:Define the Prototype Interface

The prototype interface will have a clone method to create copies of objects.

interface Prototype {
clone(): this;
}
Enter fullscreen mode Exit fullscreen mode




Step 2: Create the Concrete Prototype

This class implements the Prototype interface and define how the object will be cloned.

class GameCharacter implements Prototype {
name: string;
health: number;
armor: string;
weapons: string[];

constructor(name: string, health: number, armor: string, weapons: string[]) {
this.name = name;
this.health = health;
this.armor = armor;
this.weapons = weapons;
}
// Implementing the clone method
clone(): this {
const clone = Object.create(this);
clone.weapons = [...this.weapons]; // Deep copy of the array
return clone;
}

displayCharacter(): void {
console.log(
Character: ${this.name}, Health: ${this.health}, Armor: ${this.armor}, Weapons: ${this.weapons.join(", ")}
);
}
}

Enter fullscreen mode Exit fullscreen mode




Step 3: Client Code Example

The client creates an initial object and uses the clone method to create new instances with slight modifications.

// Create the original character
const warrior = new GameCharacter("Warrior", 100, "Steel Armor", ["Sword", "Shield"]);
warrior.displayCharacter();
// Clone the character and customize
const archer = warrior.clone();
archer.name = "Archer";
archer.health = 80;
archer.armor = "Leather Armor";
archer.weapons.push("Bow");
archer.displayCharacter();
// Clone again for another variation
const samurai = warrior.clone();
samurai.name = "Samurai";
samurai.weapons = ["Katana"];
samurai.displayCharacter();
Enter fullscreen mode Exit fullscreen mode




Real-Life Projects That Use the Prototype Pattern

The Prototype Pattern is commonly used in various domains where object creation needs to be efficient and flexible. Some examples include:

  1. Game Development
    Used to duplicate characters, weapons, or environments with minor variations.
    Example: A “boss enemy” cloned with different attack patterns or colors.

  2. Graphic Design Software
    Tools like Photoshop use this pattern to duplicate elements (e.g., shapes, layers) for reuse or modification.

  3. Document Management Systems

  4. Creating document templates that can be cloned and customized for specific needs.

  5. Database Records

  6. Cloning data objects to create slightly modified versions without affecting the original records.

Conclusion

The Prototype Pattern is a valuable tool in scenarios where creating objects from scratch is inefficient or repetitive. By cloning existing instances, you gain speed, flexibility, and consistency in object creation.

In the next article of our Learn Design Patterns series, we’ll explore the Singleton Pattern Stay tuned!

Top comments (0)