Skip to content

Instantly share code, notes, and snippets.

@myildizCH
Created July 16, 2023 16:32
Show Gist options
  • Save myildizCH/f7ab0c149b61f34801bd350568577fc2 to your computer and use it in GitHub Desktop.
Save myildizCH/f7ab0c149b61f34801bd350568577fc2 to your computer and use it in GitHub Desktop.
Prototype Pattern
// Step 1: Create a Prototype
// Create a Cloneable interface
interface Cloneable {
clone(): Cloneable;
}
// Create a GameObject class that implements Cloneable
class GameObject implements Cloneable {
constructor(private sprite: string, private position: number) {}
clone() {
return new GameObject(this.sprite, this.position);
}
describe() {
console.log(`Sprite: ${this.sprite}, Position: ${this.position}`);
}
}
// Step 2: Clone the Prototype
// Create a new object from GameObject
const alien = new GameObject('alien.png', 0);
alien.describe(); // Outputs: Sprite: alien.png, Position: 0
// Clone the object
const clonedAlien = alien.clone();
clonedAlien.describe(); // Outputs: Sprite: alien.png, Position: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment