我正在尝试基于CoffeeScript Cookbook中代表的想法开发 CoffeeScript Singleton Fetcher 。
该说明书描述了如何在 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'
我正在努力开发的东西
我正在尝试开发一种从 root.Singleton 对象中获取许多单例类的方法。像这样:
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() 都打印了“Hello A”,它们都引用了同一个 Singleton。
问题
我哪里错了?我怎样才能像上面描述的那样开发一个简单的 Singleton fetcher?