Last Updated: February 25, 2016
·
3.397K
· endel

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

4 Responses
Add your response

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 ·