Skip to content

Instantly share code, notes, and snippets.

@frontdevops
Last active August 25, 2016 08:52
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 frontdevops/482886d79f3464d8f7a62b488646c314 to your computer and use it in GitHub Desktop.
Save frontdevops/482886d79f3464d8f7a62b488646c314 to your computer and use it in GitHub Desktop.
let singleton = Symbol();
let singletonEnforcer = Symbol();
class Singleton {
constructor(enforcer) {
if (enforcer !== singletonEnforcer)
throw "Instantiation failed: use Singleton.getInstance() instead of new.";
// код конструктора
}
static get instance() {
if (!this[singleton])
this[singleton] = new Singleton(singletonEnforcer);
return this[singleton];
}
static set instance(v) { throw "Can't change constant property!" }
}
export default Singleton;
import Singleton from 'singleton';
// Test constructor
try { var obj0 = new Singleton() } catch(c) { console.log(c) }
console.log('obj0', obj0 );
// Create and get object
let obj1 = Singleton.instance;
let obj2 = Singleton.instance;
console.log(obj2.foo === 123 );
obj1.foo = 456;
console.log('obj2', obj2 );
console.log('obj1 === obj2', obj1 === obj2 );
try { var obj3 = new Singleton() } catch(c) { console.log(c) }
console.log('obj3', obj3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment