Registry Pattern in Javascript

Wer globale Objekte vermeiden will, aber trotzdem globalen Zugriff will (z.B. auf eine Datenbankinstanz) baut sich eine Registry. Im Prinzip nur das Singleton-Pattern mit get und set-Methoden:

registry = (function() {
	// private attributes
	var blubb = new Array();
	// private methods
	var getIndex = function(_name) {
		for (var i = 0; i < blubb.length; i++) {
			if (blubb[i].name == _name) {
				return i;
			}
		}
		return null;
	};

	return {
		// public attributes

		// public methods
		setValue : function(_name, _value) {
			var foo = this.getValue(_name);
			if (foo == null) {
				var temp = new Object();
				temp.name = _name;
				temp.value = _value;
				blubb.push(temp);
			} else {
				blubb[getIndex(_name)].value = _value;
			}
		},
		getValue : function(_name) {
			for (var i = 0; i < blubb.length; i++) {
				if (blubb[i].name == _name) {
					return blubb[i].value;
				}
			}
			return null;
		}
	}
})();
// registry is already available
registry.setValue("foo", "bar");
registry.getValue("foo"); // gives "bar"
registry.getValue("bar"); // gives null
[/sourcecode]

Siehe auch: http://yuiblog.com/blog/2007/06/12/module-pattern/