Skip to content

Instantly share code, notes, and snippets.

@sebslomski
Forked from meltingice/singleton.coffee
Created May 19, 2011 12:47
Show Gist options
  • Save sebslomski/980669 to your computer and use it in GitHub Desktop.
Save sebslomski/980669 to your computer and use it in GitHub Desktop.
Example singleton class and example for Coffeescript
class Singleton
# We can't make private variables!
__instance = null
# Static singleton retriever/loader
@get: ->
if not @__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 (!(this.__instance != null)) {
this.__instance = new this;
this.__instance.init();
}
return this.__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