nsyuia
Last Updated: February 25, 2016
·
3.144K
· endel
Profile 2015 2

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
Say Thanks
Respond

4 Responses
Add your response

1258
35afc3a

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
169e628d2201b2eba37bb8a7e1ab9893

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

over 1 year ago ·
4020
Profile 2015 2

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

over 1 year ago ·
16865
None

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 ·
Awesome Job

B6c77ad0 c95b 11e7 8263 8f89080b8db6
Ruby Developer Backend
·
Austria (Vienna or Linz)
·
Full Time