我正在尝试基于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