Created
March 25, 2012 14:01
-
-
Save benshimmin/2194809 to your computer and use it in GitHub Desktop.
Singletons in CoffeeScript
This file contains hidden or 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
# CoffeeScript makes this almost uniquely easy. | |
class Singleton | |
instance = undefined | |
@getInstance : -> | |
instance ?= new @ | |
# And a singleton class can be subclassed elegantly too. | |
class SingletonTest extends Singleton | |
constructor : -> | |
@property = 100 | |
t1 = SingletonTest.getInstance() | |
console.log t1.property # -> 100 | |
t1.property = 200 | |
t2 = SingletonTest.getInstance() | |
console.log t2.property # -> 200 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment