Acho que este não é o padrão mais rápido, mas é o mais legível e compreensível para mim.
O código a seguir é autoexplicativo. Eu comentei linha a linha.
Para ver este código funcionando, siga http://jsfiddle.net/DknAX/1/ e observe seu console.
// All functions have now the compose method
Function.prototype.compose = function(argFunction) {
var invokingFunction = this;
return function() {
return invokingFunction.call(this,argFunction.apply(this,arguments));
}
}
// For things who work as an electronic
var asEletronic = function() {
// Exclusive eletronic property
this.on = false;
// Exclusive eletronic property
this.voltage = 110;
// Exclusive eletronic method
this.switchPower = function() {
if(this.on === true) {
this.on === false;
console.info('Eletronic is OFF');
} else {
this.on === true;
console.info('Eletronic is ON');
}
}
}
// For things who work as an sound reproducer
var asSoundReproducer = function() {
// Exclusive sound reproducer property
this.mp3Support = true;
// Exclusive sound reproducer property
this.volume = 10;
// Exclusive sound reproducer method
this.increaseVolume = function() {
this.volume++;
console.info('Volume increased to: ' + this.volume);
}
this.decreaseVolume = function() {
this.volume--;
console.info('Volume decreased to: ' + this.volume);
}
}
var TV = function() {
console.info('New TV instantiated');
// Core TV property
this.pol = 42;
// Core TV property
this.fullHD = true;
}
var MicroSystem = function() {
console.info('New Micro System instantiated');
// Core micro system property
this.station = 102.9;
// Core micro system method
this.setStation = function(newStation) {
this.station = newStation;
console.info('Micro System are now in station ' + newStation);
}
}
// Composing a TV
// TV works like a eletronic
TV = TV.compose(asEletronic);
// TV works like a sound reproducer
TV = TV.compose(asSoundReproducer);
// Composing a Micro System
// Micro system works like a eletronic
MicroSystem = MicroSystem.compose(asEletronic);
// Micro system works like a sound reproducer
MicroSystem = MicroSystem.compose(asSoundReproducer);
// A new TV instantiation
var myTV = new TV();
// Logging myTV to see what it have inside
console.log(myTV);
// A new Micro System instantiation
var myMicroSystem = new MicroSystem();
// Logging myMicroSystem to see what it have inside
console.log(myMicroSystem);
// Turn on my TV
myTV.switchPower();
// Increasing TV volume
myTV.increaseVolume();
// Turn on my Mycro System
myMicroSystem.switchPower();
// Logging current station
console.info('Current station: ' + myMicroSystem.station);
// Setting a new station
myMicroSystem.setStation(88.5);
// Logging current station
console.info('Current station: ' + myMicroSystem.station);