我正在嘗試基於CoffeeScript Cookbook中表示的想法開發CoffeeScript Singleton Fetcher。試圖開發CoffeeScript Singleton Fetcher
菜譜介紹瞭如何實現一個singlelton類的CoffeeScript以及如何從全局命名空間獲取該班,像這樣:
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'
我試圖開發
我m試圖開發一種方法來從root.Singleton對象中獲取許多singlton類。像這樣:
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'
的目標是通過聲明獲得單:
root.Singleton 'Constructor Args' 'Singleton name'
的問題
不幸的是a.echo()和b.echo()都打印「你好A',它們都是引用同一個Singleton。
問題
我要去哪裏錯了?我如何開發一個像我上面描述的簡單的Singleton fetcher?
因此,這實際上是一個「單身工廠」呢? – robkuz 2013-02-17 16:25:19
是的,我無法在網上找到Singleton Factories for CoffeeScript的任何好的實現。 – 2013-02-17 16:33:12