prototype design pattern typescript 1

prototype design pattern typescript

interface IPrototype {
	getClone(): InstanceType
}

class Person implements IPrototype {
	public name: string
	public age: number
	public hobby: string

	constructor(name: string, age: number, hobby: string) {
		this.name = name
		this.age = age
		this.hobby = hobby
	}

	public getClone(): InstanceType {
		return this
	}
}

const john: Person = new Person('john doe', 30, 'programming')
console.log(john)

const jane = john.getClone()
jane.name = 'jane doe'
jane.hobby = 'swimming'

console.log(jane)

const ari = john.getClone()
ari.name = 'ari gunawan'
ari.age = 25
ari.hobby = 'music'

console.log(ari)

Here is what the above code is Doing:
1. We have a class called Person.
2. We have an interface called IPrototype.
3. We have a method called getClone() that returns an instance of the Person class.
4. We have a variable called john that is an instance of the Person class.
5. We have a variable called jane that is a clone of the john variable.
6. We have a variable called ari that is a clone of the john variable.
7. We change the name, age, and hobby of the jane variable.
8. We change the name, age, and hobby of the ari variable.
9. We log the john, jane, and ari variables to the console.

Similar Posts