Skip to content

Instantly share code, notes, and snippets.

@dmnsgn
Created April 16, 2016 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmnsgn/0f7cd0641132fb99c50dd380d4febfce to your computer and use it in GitHub Desktop.
Save dmnsgn/0f7cd0641132fb99c50dd380d4febfce to your computer and use it in GitHub Desktop.
ES6 singleton pattern: prevent the creation of an instance
// Implementation 4: prevent the creation of an instance
class SingletonNoInstance {
constructor(enforcer) {
throw new Error('Cannot construct singleton');
}
static singletonMethod() {
return 'singletonMethod';
}
static staticMethod() {
return 'staticMethod';
}
}
SingletonNoInstance.type = 'SingletonNoInstance';
export default SingletonNoInstance;
// ...
// index.js
import SingletonNoInstance from './SingletonNoInstance';
// Instantiate
// console.log(new SingletonNoInstance); // Cannot construct singleton
// Prototype Method
console.log(SingletonNoInstance.type, SingletonNoInstance.singletonMethod());
// Object property
SingletonNoInstance.type = 'type updated'; // Not using getter/setters
console.log(SingletonNoInstance.type); // Not using getter/setters
// Static method
console.log(SingletonNoInstance.staticMethod());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment