Skip to content

Instantly share code, notes, and snippets.

@Shamaoke
Created March 16, 2012 13:13
Show Gist options
  • Save Shamaoke/2050022 to your computer and use it in GitHub Desktop.
Save Shamaoke/2050022 to your computer and use it in GitHub Desktop.
CoffeeScript Singleton
# class
class Singleton
constructor: ->
throw new Error 'Singleton error' if @.constructor is Singleton or @.constructor._instance
@.constructor._instance = @
@instance: (arg...) ->
unless @._instance
new @ arg...
else
@._instance
# spec
describe 'Singleton', ->
describe 'constructor', ->
it 'throws an error when trying to create a Singleton instance', ->
(-> new Singleton).should.throw 'Singleton error'
it 'does not throw an error when trying to create a Singelton subclass instance', ->
class Example extends Singleton
constructor: -> super
(-> new Example).should.not.throw 'Singleton error'
it 'throws an error when trying to create a Singleton subclass more than once', ->
class Example extends Singleton
constructor: -> super
new Example; (-> new Example).should.throw 'Singleton error'
describe 'instance', ->
it 'creates an instance of a Singleton subclass', ->
class Example extends Singleton
constructor: -> super
Example.instance().should.be.an.instanceof Example
it 'returns an instance of a Singleton subclass if it was already created', ->
class Example extends Singleton
constructor: -> super
Example.instance().should.equal Example.instance()
it 'passes arguments to the constructor', ->
class Example extends Singleton
constructor: (one, two) ->
@data = [one, two]
super
Example.instance('ok!', 'ok too!').data.should.eql ['ok!', 'ok too!']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment