Created
April 16, 2016 17:46
-
-
Save dmnsgn/0f7cd0641132fb99c50dd380d4febfce to your computer and use it in GitHub Desktop.
ES6 singleton pattern: prevent the creation of an instance
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
// 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