Singleton Pattern on Coffeescript
Singleton definition:
class Singleton
@getInstance: ->
@_instance ?= new @(arguments...)
Our singleton class:
class Manager extends Singleton
constructor: (arg) ->
@arg = arg
First call, initialize it.
manager = Manager.getInstance("hello")
console.log(manager.arg) # hello
Second call, just return the instance.
manager = Manager.getInstance("world")
console.log(manager.arg) # hello
Written by Endel Dreyer
Related protips
4 Responses

You'd need to add additional code in a constructor for Manager to ensure there is only one instance or that getInstance
is always used.
over 1 year ago
·

The idea that people are adding new singletons to their code is something that worries me greatly.
over 1 year ago
·

@SamirTalwar ok, share what you think it's right instead
over 1 year ago
·

What about this approach:
class Singleton
@getInstance: ->
@_instance ?= new @(@,arguments...)
constructor: (args...) ->
unless @constructor == args.shift()
throw new Error('Cannot call new on a Singleton')
return args
class Manager extends Singleton
constructor: ->
[@arg] = super
It makes new Manager()
unlikely.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Design patterns
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#