Created
March 16, 2012 13:13
-
-
Save Shamaoke/2050022 to your computer and use it in GitHub Desktop.
CoffeeScript Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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