Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton class in coffeescript

I use singleton pattern class in coffeescript which shown below recently. It works perfectly but I don't know why this could be a singleton pattern. This might be a stupid question but thanks for your answering.

#coffeescript
class BaseClass
  class Singleton

  singleton = new Singleton()
  BaseClass = -> singleton

a = new BaseClass()
a.name = "John"
console.log a.name # "John"
b = new BaseClass()
b.name = "Lisa"
console.log b.name # "Lisa"
console.log a.name # "Lisa"

and code below is javascript which is produced by the code above

var BaseClass, a, b;

BaseClass = (function() {
  var Singleton, singleton;

  function BaseClass() {}

  Singleton = (function() {
    function Singleton() {}

    return Singleton;

  })();

  singleton = new Singleton();

  BaseClass = function() {
    return singleton;
  };

  return BaseClass;

})();

a = new BaseClass();

a.name = "John";

console.log(a.name);

b = new BaseClass();

b.name = "Lisa";

console.log(b.name);

console.log(a.name);

EDITED : I am not asking the definition of 'singleton pattern' nor how they are generally created but the reason why the code above always returns the same instance instead of creating new one.

like image 323
suish Avatar asked Sep 14 '14 00:09

suish


1 Answers

First of all, there is a good example of Singleton Pattern implementation in CoffeeScript Cookbook:

class Singleton
  instance = null

  class PrivateClass
    constructor: (@message) ->
    echo: -> @message

  @get: (message) ->
    instance ?= new PrivateClass(message)

You tried to do a similar thing, but messed with CoffeeScript syntax a little bit. Here is how it should look:

class BaseClass
  class Singleton

  singleton = new Singleton()

  constructor: ->
    return singleton

Note that I'm using an explicit return here. I'm doing it because CoffeeScript implicit return doesn't work for class constructors.

I would also recommend you to take a look at Simplest/Cleanest way to implement singleton in JavaScrip question.

My favorite singleton implementation is the following one:

class BaseClass
  instance = null

  constructor: ->
    if instance
      return instance
    else
      instance = this
    # contructor code

It works like yours except for two things:

  • it doesn't require an additional class definition;
  • it creates first singleton instance only when it's needed.
like image 90
Leonid Beschastny Avatar answered Oct 04 '22 21:10

Leonid Beschastny