试图开发CoffeeScript Singleton Fetcher

时间:2013-02-17 16:01:32

标签: coffeescript singleton

我正在尝试根据CoffeeScript Cookbook中表示的想法开发CoffeeScript Singleton Fetcher。

本教程描述了如何在CoffeeScript中实现singlelton类以及如何从全局命名空间中获取该类,如下所示:

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对象中获取许多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()都打印'Hello A',它们都引用了相同的Singleton。

问题

我哪里错了?我怎样才能像上面描述的那样开发一个简单的Singleton fetcher?

2 个答案:

答案 0 :(得分:3)

据我所知,你正在覆盖你的“单一”实例。 所以你至少需要一些容器来容纳你的“很多”单身人士 以后访问它们。

class root.Singleton
    @singletons = 
        Singleton1: Singleton1
        Singleton2: Singleton2
    @instances = {}
    @get: (name, args...) -> # Must be a static method
        @instances[name] ||= new @singletons[name] args...

你称之为“fetcher”的是工厂模式。

答案 1 :(得分:1)

感谢围绕@args / args...和单身人士的好例子。

只是像我这样的CoffeeScript新手,在这个例子中我们需要将调用顺序(args...更改为结尾):

a = root.Singleton.get 'Singleton1', 'Hello A'
a.echo()
# => 'Hello A'

b = root.Singleton.get 'Singleton2', 'Hello B'
b.echo()
# => 'Hello B'