nsyuia
Last Updated: February 25, 2016
·
3.209K
· 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

1258

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 ·
4010

The idea that people are adding new singletons to their code is something that worries me greatly.

over 1 year ago ·
4020

@SamirTalwar ok, share what you think it's right instead

over 1 year ago ·
16865

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 ·