Last active
February 17, 2019 22:15
-
-
Save andreasonny83/c049dd8264bda7e56e384df82986cd68 to your computer and use it in GitHub Desktop.
Singleton Pattern
This file contains hidden or 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
/** | |
* The singleton pattern is a pattern used to restrict an object to a single instance. | |
* A singleton creates an instance of an object if that object does not exist. | |
* If it exists it returns the existing instance. | |
*/ | |
class Car { | |
constructor(model, year, miles) { | |
if(Car.exists){ | |
return Car.instance | |
} | |
this.model = model; | |
this.year = year; | |
this.miles = miles; | |
Car.exists = true; | |
Car.instance = this; | |
return this | |
} | |
toString(){ | |
return this.model + " has done " + this.miles + " miles"; | |
} | |
} | |
// Usage: | |
let civic = new Car( "Honda Civic", 2009, 20000 ); | |
let mondeo = new Car( "Ford Mondeo", 2010, 5000 ); | |
console.log( civic.toString() ); // Honda Civic has done 20000 miles | |
console.log( mondeo.toString() ); // Honda Civic has done 20000 miles |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment