Trying to develop a CoffeeScript Singleton Fetcher cooler
I am trying to develop a CoffeeClick Singleton Fetcher based on an idea presented in the Coffeebook Cookbook .
The cookbook describes how to implement the singlelton class in CoffeeScript and how to get that class from the global namespace, for example:
root = exports ? this
# The publicly accessible Singleton fetcher
class root.Singleton
_instance = undefined # Must be declared here to force the closure on the class
@get: (args) -> # Must be a static method
_instance ?= new _Singleton args
# The actual Singleton class
class _Singleton
constructor: (@args) ->
echo: ->
@args
a = root.Singleton.get 'Hello A'
a.echo()
# => 'Hello A'
What i am trying to develop
I am trying to work out a way to extract many singlton classes from root.Singleton object. For example:
root = exports ? this
# The publicly accessible Singleton fetcher
class root.Singleton
_instance = undefined # Must be declared here to force the closure on the class
@get: (args, name) -> # Must be a static method
switch name
when 'Singleton1' then _instance ?= new Singleton1 args
when 'Singleton2' then _instance ?= new Singleton2 args
else console.log 'ERROR: Singleton does not exist'
# The actual Singleton class
class Singleton1
constructor: (@args) ->
echo: ->
console.log @args
class Singleton2
constructor: (@args) ->
echo: ->
console.log @args
a = root.Singleton.get 'Hello A', 'Singleton1'
a.echo()
# => 'Hello A'
b = root.Singleton.get 'Hello B', 'Singleton2'
b.echo()
# => 'Hello B'
The goal is to get a singleton by declaring:
root.Singleton 'Constructor Args' 'Singleton name'
Problem
Unfortunately a.echo () and b.echo () both print 'Hello A', they both refer to the same Singleton.
Question
Where am I going wrong? How can I design a simple singleton picker like I described above?
source to share
As far as I can see, you are overwriting your "one" copy. Thus, you need at least some kind of container to store your "many" singlets and to access them later.
class root.Singleton
@singletons =
Singleton1: Singleton1
Singleton2: Singleton2
@instances = {}
@get: (name, args...) -> # Must be a static method
@instances[name] ||= new @singletons[name] args...
What you call "receiver" is a factory pattern.
source to share
thanks for the nice example about @args
/ args...
and singleton.
just for those new to CoffeeScript like me, in this example we need to change the order of the call ( args...
to the end):
a = root.Singleton.get 'Singleton1', 'Hello A'
a.echo()
# => 'Hello A'
b = root.Singleton.get 'Singleton2', 'Hello B'
b.echo()
# => 'Hello B'
source to share