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
- Prototype: An object that can create a copy of itself.
- 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
Original Car:
Car: Toyota Corolla (2020)
Cloned Car:
Car: Toyota Corolla (2020)
Modified Cloned Car:
Modified Car: Toyota Corolla (2020) - Custom
Original Car after cloning:
Car: Toyota Corolla (2020)
Explanation
- Prototype Interface: Defines the
clonemethod that all prototypes must implement. - Car Class: Implements the
Prototypeinterface and theclonemethod. It also has adisplaymethod to show the car’s details. - Client Code: Creates an original
Carobject and then clones it using theclonemethod. 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.
Leave a Reply