2013-02-17 54 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'