Skip to content

Instantly share code, notes, and snippets.

@thissideup
Created December 20, 2012 15:03
Show Gist options
  • Save thissideup/4345783 to your computer and use it in GitHub Desktop.
Save thissideup/4345783 to your computer and use it in GitHub Desktop.
A take on managed/pooled objects. A lot simpler (naive?) than https://github.com/playcraft/gamecore.js/blob/master/src/pooled.js Will have to compare performance… On the other hand — plays well with the closure compiler's advanced optimizations. https://github.com/playcraft/gamecore.js/blob/master/src/pooled.js
'use strict';
/**
* Base class for managed objects. It expects it's descendants to have a pool
* array. Initialization and de-initialization logic should be moved to the
* initInternal and releaseInternal.
* Managed objects are marked as reusable by a call to the release method.
*/
var Managed = function() {
if (this.pool.length > 0) {
return this.pool.shift();
} else {
this.initInternal.apply(this, arguments);
return this;
}
};
Managed.prototype.initInternal = function() {
};
Managed.prototype.release = function() {
this.releaseInternal();
this.pool.push(this);
};
Managed.prototype.releaseInternal = function() {
};
/**
* A managed class. Reuse of instances is demonstrated by the private id field.
* It also contains a public color field, that should be (but isn't) reset
* inside the releaseInternal method.
*/
var Id = function(color) {
return Managed.call(this, color);
};
function tempCtor() {}
tempCtor.prototype = Managed.prototype;
Id.superClass_ = Managed.prototype;
Id.prototype = new tempCtor();
/** @override */
Id.prototype.constructor = Id;
Id.id_ = 0;
Id.prototype.valueOf = function() {
return this.id_
};
Id.prototype.pool = [];
Id.prototype.initInternal = function(color) {
this.id_ = Id.id_++;
this.color = color || this.color;
};
/*
*
*/
var i0 = new Id('pink');
console.log(i0); // id: 0, color: pink
var i1 = new Id('red');
console.log(i1); // id: 1, color: red
i0.release();
console.log(i0); // id: 0, color: pink
var i2 = new Id();
console.log(i2); // id: 0, color: pink
console.log(i2 == i0); // true
i0 = null;
console.log(i0); // null
var i3 = new Id('magenta');
console.log(i3); // id: 2, color: magenta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment