2013-02-17 59 views
3

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

+0

因此,这实际上是一个“单身工厂”呢? – robkuz 2013-02-17 16:25:19

+0

是的,我无法在网上找到Singleton Factories for CoffeeScript的任何好的实现。 – 2013-02-17 16:33:12

回答

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”的是工厂模式。

+0

你的'@ get'可能只是'@instances [name] || = new @singletons [name] args ...',不是?您还可以将'@ get'更改为'@get:(name,args ...)'以获得更自然的(IMO)接口。所有这些只是尼特采摘:) – 2013-02-18 06:42:41

+0

是的,你是对的 – robkuz 2013-02-18 07:29:56

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'