Skip to content

Instantly share code, notes, and snippets.

@storyn26383
Created June 29, 2020 10:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save storyn26383/3d4abd5a6d870514bfadecc767547c12 to your computer and use it in GitHub Desktop.
Save storyn26383/3d4abd5a6d870514bfadecc767547c12 to your computer and use it in GitHub Desktop.
class Container {
static get proxyHandler () {
return {
get (target, prop) {
if (prop in target) {
return Reflect.get(...arguments)
}
return target.resolve(prop)
}
}
}
static getInstance () {
if (!this.instance) {
this.instance = new Proxy(new this, this.proxyHandler)
}
return this.instance
}
constructor () {
this.bindings = []
this.instances = []
}
singleton (abstract, concrete) {
this.bindings[abstract] = concrete
}
instance (abstract, instance) {
this.instances[abstract] = instance
}
resolve (abstract) {
if (abstract in this.bindings && !(abstract in this.instances)) {
this.instances[abstract] = this.bindings[abstract]()
}
return this.instances[abstract]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment