The Dev Journey

Prototype aka Clone Design Pattern using Typescript

The Prototype design pattern is a creational pattern that allows you to create new objects by copying existing objects, known as prototypes. This pattern is useful when the cost of creating a new object is expensive, or when you want to avoid the complexity of creating a new object from scratch.

Key Concepts

  1. Prototype: An object that can create a copy of itself.
  2. Client: The code that uses the prototype to create new objects.

When to Use

  • When the creation of an object is expensive or complex.
  • When you want to avoid subclassing to create new objects.
  • When you need to create objects that are similar to existing objects.

Typescript Example

Let’s create a simple example in TypeScript to demonstrate the Prototype design pattern. We’ll create a Car class that implements a clone method to create copies of itself.

// Define the Prototype interface
interface Prototype {
    clone(): Prototype;
}

// Concrete Prototype class
class Car implements Prototype {
    private make: string;
    private model: string;
    private year: number;

    constructor(make: string, model: string, year: number) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Clone method to create a copy of the object
    clone(): Car {
        return new Car(this.make, this.model, this.year);
    }

    // Method to display car details
    display(): void {
        console.log(`Car: ${this.make} ${this.model} (${this.year})`);
    }
}

// Client code
const originalCar = new Car('Toyota', 'Corolla', 2020);
console.log('Original Car:');
originalCar.display();

const clonedCar = originalCar.clone();
console.log('Cloned Car:');
clonedCar.display();

// Modify the cloned car to see if it affects the original
clonedCar.display = function() {
    console.log(`Modified Car: ${this.make} ${this.model} (${this.year}) - Custom`);
};

console.log('Modified Cloned Car:');
clonedCar.display();

console.log('Original Car after cloning:');
originalCar.display();

Output

Explanation

  1. Prototype Interface: Defines the clone method that all prototypes must implement.
  2. Car Class: Implements the Prototype interface and the clone method. It also has a display method to show the car’s details.
  3. Client Code: Creates an original Car object and then clones it using the clone method. It demonstrates that modifying the cloned object does not affect the original object.

This example shows how the Prototype design pattern can be used to create new objects by copying existing ones, ensuring that changes to the cloned object do not affect the original object.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *