Skip to content

Instantly share code, notes, and snippets.

@andreasonny83
Last active February 17, 2019 22:15
Show Gist options
  • Save andreasonny83/c049dd8264bda7e56e384df82986cd68 to your computer and use it in GitHub Desktop.
Save andreasonny83/c049dd8264bda7e56e384df82986cd68 to your computer and use it in GitHub Desktop.
Singleton Pattern
/**
* 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