Design Patterns
Andrés Bedoya (@Angel_fire)
A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript web applications. Another way of looking at patterns are as templates for how we solve problems - ones which can be used in quite a few different situations.
Addy Osmani
Design Patterns: Elements of Reusable Object-Oriented Software - 1994
GoF (Gang of Four)
23 patterns:
Abstract Factory
Builder
Factory Method
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Chain of Responsability
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template
Visitor
function Persona (nombre, apellido, edad, perfil, idioma) {
this.nombre = nombre;
this.apellido = apellido;
this.edad = edad;
this.perfil = perfil;
this.idioma = idioma || "Ingles";
this.fullName = function () {
return this.nombre + " " + this.apellido;
}
}
Persona.prototype.fullInfo = function() {
return this.nombre + " " + this.apellido + " Tiene " +
this.edad + " años" + " Se desempeña como " + this.perfil +
" Y habla " + this.idioma;
}
var persona1 = new Persona ("Andres", "Bedoya", 30, "UI developer", "Ingles");
console.log(persona1.fullName());
console.log(persona1.fullInfo());
In JavaScript, there are several options for implementing modules. These include:
var myModuleJS = {
myConfig: {
language: "es",
country: "Colombia",
cache: true
},
reportMyConfig: function () {
console.log("Caching is: " + (this.myConfig.cache ? "enabled" : "disabled"));
console.log("Language: " + this.myConfig.language);
console.log("Country: " + this.myConfig.country);
},
updateMyConfig: function(newConfig) {
if (typeof newConfig === "object") {
this.myConfig = newConfig;
}
}
};
myModuleJS.reportMyConfig();
myModuleJS.updateMyConfig({
language: "en",
country: "England",
cache: false
});
myModuleJS.reportMyConfig();
var myRevealingModule = (function() {
// Private method
var calculateSalary = function (name, basicSalary) {
if (basicSalary > 499) {
if (name.length > 6) {
return basicSalary - 40;
} else {
return basicSalary - 20;
}
} else {
return basicSalary + 20;
}
};
// Public method
var finalSalary = function (name, basicSalary) {
return calculateSalary(name, basicSalary);
};
return {
printSalary: finalSalary
};
})();
myRevealingModule.printSalary("Andres", 500);
AMD (Asynchronous Module Definition) format is to provide a solution for modular JavaScript that developers can use today.