Skip to content

Instantly share code, notes, and snippets.

@irohiroki
Forked from meltingice/singleton.coffee
Created December 1, 2011 02:11
Show Gist options
  • Save irohiroki/1412821 to your computer and use it in GitHub Desktop.
Save irohiroki/1412821 to your computer and use it in GitHub Desktop.
Example singleton class and example for Coffeescript
class Singleton
# We can make private variables!
instance = null
# Static singleton retriever/loader
@get: ->
unless instance
instance = new @
instance.init()
instance
# Example class method for debugging
init: (name = "unknown") ->
console.log "#{name} initialized"
class Test extends Singleton
init: ->
super "Test"
run: ->
alert "OHAI"
class OtherTest extends Singleton
init: ->
super "Other Test"
run: ->
alert "WUT"
Test.get().run()
OtherTest.get().run()
Test.get().run()
var OtherTest, Singleton, Test;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
Singleton = (function() {
var instance;
function Singleton() {}
instance = null;
Singleton.get = function() {
if (!instance) {
instance = new this;
instance.init();
}
return instance;
};
Singleton.prototype.init = function(name) {
if (name == null) name = "unknown";
return console.log("" + name + " initialized");
};
return Singleton;
})();
Test = (function() {
__extends(Test, Singleton);
function Test() {
Test.__super__.constructor.apply(this, arguments);
}
Test.prototype.init = function() {
return Test.__super__.init.call(this, "Test");
};
Test.prototype.run = function() {
return alert("OHAI");
};
return Test;
})();
OtherTest = (function() {
__extends(OtherTest, Singleton);
function OtherTest() {
OtherTest.__super__.constructor.apply(this, arguments);
}
OtherTest.prototype.init = function() {
return OtherTest.__super__.init.call(this, "Other Test");
};
OtherTest.prototype.run = function() {
return alert("WUT");
};
return OtherTest;
})();
Test.get().run();
OtherTest.get().run();
Test.get().run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment