Created
July 16, 2023 16:32
-
-
Save myildizCH/f7ab0c149b61f34801bd350568577fc2 to your computer and use it in GitHub Desktop.
Prototype Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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