Prototype Pattern
Posted by Dustin Boston in Design Patterns.
The Prototype Pattern is a creational design pattern that facilitates object cloning, enabling the creation of new objects by copying existing ones and promoting flexibility in object creation.
The Prototype Pattern is a creational design pattern that enables object cloning,
allowing new objects to be created by copying existing ones. This pattern is
particularly useful when object creation is resource-intensive or when objects
need to be customized without altering their structure.
Source Code Listing
code.ts
type Prototype = {
clone(): Prototype;
setProperty(property: string): void;
logProperty(): void;
};
class ConcretePrototype1 implements Prototype {
property: string | undefined; // Make property optional
clone(): ConcretePrototype1 {
const cloned = new ConcretePrototype1();
cloned.property = this.property; // Deep copy of property
return cloned;
}
setProperty(property: string): void {
this.property = property;
}
logProperty(): void {
console.log(this.property ?? "-");
}
}
class ConcretePrototype2 implements Prototype {
property: string | undefined;
clone(): ConcretePrototype2 {
const cloned = new ConcretePrototype2();
cloned.property = this.property;
return cloned;
}
setProperty(property: string): void {
this.property = property;
}
logProperty(): void {
console.log(this.property || "-");
}
}
class Client {
operation(prototype: Prototype): Prototype {
return prototype.clone();
}
}
const example = {
run(): void {
const client = new Client();
const cp1 = new ConcretePrototype1();
const cp1Prototype = client.operation(cp1);
cp1.setProperty("original1");
cp1Prototype.setProperty("clone1");
cp1.logProperty();
cp1Prototype.logProperty();
const cp2 = new ConcretePrototype2();
const cp2Prototype = client.operation(cp2);
cp2.setProperty("original2");
cp2Prototype.setProperty("clone2");
cp2.logProperty();
cp2Prototype.logProperty();
},
};
example.run();