如何创buildcoffeescript单例子类
我创build了一个我想要扩展的单例类。 它(一半)的工作原理是它只创build一个类的单个实例,但添加到子类的属性是未定义的。 这是原来的单身人士:
class Singleton _instance = undefined @getInstance: -> if _instance is undefined console.log 'no instance exists, so create one' _instance = new _Singleton() else console.log 'an instance already exists.' class _Singleton constructor: -> console.log 'new singelton' module.exports = Singleton
这里是子类:
Singleton = require('./singleton') class Stinky extends Singleton constructor: -> var1 : 'var1' module.exports = Stinky
现在,如果我在我的节点应用程序中使用以下:
Stinky = require './stinky' thing1 = Stinky.getInstance() thing2 = Stinky.getInstance() console.log "Thing var1: #{thing1.var1}"
getInstance()方法的行为与预期相同,但是var1是未定义的。 如果我在非单身人士class上做同样的事情,他们工作得很好。 谢谢。
我修剪了一下你的代码。 剩下的两个class:
class Singleton @_instance: null @getInstance: -> @_instance or= new @( arguments... ) class Stinky extends Singleton constructor: ( @num ) -> thing1 = Stinky.getInstance( 1 ) thing2 = Stinky.getInstance( 2 ) console.log( thing1.num, thing2.num )
我做了以下更改:
- 合并单身人士和_Singleton
- 将_instance更改为@_instance,以便将其连接到Singleton而不是其原型
- 在getInstance中添加参数splat(在需要参数的情况下)
- 将getInstance()指向扩展对象而不是Singleton
在这个例子中,我使用了2个不同的数字来确保第二个构造函数从来没有被调用。
我看到你是如何使用_Singleton
类来模拟一个私人类,但不幸的是,我不认为你可以在这种情况下使用它。
以下是一些可用的代码:
class Singleton _instance = undefined constructor: -> console.log 'new singleton' @getInstance: -> if _instance is undefined console.log 'no instance exists, so create one' _instance = new @() else console.log 'an instance already exists.' _instance class Stinky extends Singleton constructor: -> console.log 'Stinky constructor' @var1 = 'var1' thing1 = Stinky.getInstance() thing2 = Stinky.getInstance() console.log "Thing var1: #{thing1.var1}", thing1, thing2
我删除了Node.js(require)代码,但是添加它应该很简单。 主要区别在于我的代码创build的实例是@
或this
一个实例。 这样做将确保您的构造函数被调用,然后继续母链。 你的代码是明确地创build_Singleton
一个实例,所以你的Stinky
构造函数永远不会被调用。 你最终会注意到的另一个小问题是你的getInstance
方法实际上并没有返回_instance
一个实例。
我希望这有帮助,
桑德罗
我不确定目标是什么,但是通过使Singleton
成为一个真正的单例(一个普通的对象),你可以达到同样的结果:
Singleton = doNothing: -> # ... doMoreNothing: -> # ... class Stinky constructor: -> @var1: 'var1' getInstance: -> return Singleton
Singleton
有一个返回自己的方法没有什么意义。