javascript design patterns; The Constructor pattern and the Observer pattern


Design patterns are patterns that can be commonly applied in software development. For something to be considered a standard it must meet three basic criteria: it must be a proven solution, it is easily reusable and it can be used in many different systems. The revealing model pattern and the Singleton Pattern that we'll talk about today is no exception to this rule.

The Constructor pattern

The constructor pattern is a simple pattern. Constructor objects are a special type of function, responsible for instantiating a new object and allocating memory space for it. In javascript there is no concept of conventional classes, as we see in object-oriented languages. But there are some ingenious ways to achieve the same effects.


function Car( model, year, miles ) {

this.model = model;

this.year = year;

this.miles = miles;

this.toString = function () {

return this.model + " has done " + this.miles + " miles";


} // Usage: // We can create new instances of the car

var civic = new Car( "Honda Civic", 2009, 20000 );

var mondeo = new Car( "Ford Mondeo", 2010, 5000 ); // and then open our browser console to view the// output of the toString() method being called on// these objects

console.log( civic.toString() );

console.log( mondeo.toString() );

_______ models of the book "Learning JavaScript Design Patterns - Addy Osmani 2012-2020."

The example above shows how we can achieve the effect of the constructor pattern in javascript. By adding the 'new' keyword earlier to a constructor function we tell javascript that we would like that function to behave like a constructor. Inside the constructor, the keyword 'this' is responsible for referencing the new object being created.

The Observer Pattern

The concept of the observer pattern says that an instance maintains a list with a collection of observers (objects) and notifies them of any changes in their state. When an instance (also known as a subject ) needs to notify some event, it sends to all observers in the form of a broadcast. Another way of thinking is this: Observers are like people and instance is the subject that people can be interested in. As an observer, your job is to stay on top of the news that the issues bring. Therefore, every time there is a change in the subject that you are interested in, you will be notified and you can take action based on that. Subject: maintains a list of watchers, makes it easy to add or remove watchers Observer: Provides an updated interface for objects that need to be notified of a Subject's state changes ConcreteSubject: transmits notifications to observers about state changes, stores the state of ConcreteObservers ConcreteObserver: stores a reference to ConcreteSubject, implements an updated interface to Observer to ensure the state is consistent with Subject.


//Primeiro, vamos modelar a lista de Observadores dependentes que um sujeito pode ter:

function ObserverList(){

this.observerList = [];


ObserverList.prototype.add = function( obj ){

return this.observerList.push( obj );


ObserverList.prototype.count = function(){

return this.observerList.length;


ObserverList.prototype.get = function( index ){

if( index > -1 && index < this.observerList.length ){

return this.observerList[ index ];


ObserverList.prototype.indexOf = function( obj, startIndex ){

var i = startIndex;

while( i < this.observerList.length ){ if( this.observerList[i] === obj ){

return i;



} return -1;


ObserverList.prototype.removeAt = function( index ){ this.observerList.splice( index, 1 );


//A seguir, vamos modelar o Assunto e a capacidade de adicionar, remover ou notificar observadores na lista de observadores.

function Subject(){

this.observers = new ObserverList();


Subject.prototype.addObserver = function( observer ){

this.observers.add( observer );


Subject.prototype.removeObserver = function( observer ){

this.observers.removeAt( this.observers.indexOf( observer, 0 ) );


Subject.prototype.notify = function( context ){

var observerCount = this.observers.count(); for(var i=0; i < observerCount; i++){

this.observers.get(i).update( context );


//Em seguida, definimos um esqueleto para a criação de novos Observadores. A funcionalidade de atualização aqui será substituída posteriormente pelo comportamento personalizado.

// The Observer

function Observer(){

this.update = function(){ // ... };

}In our sample app using the Observer components above, we've now defined: A button to add new observable checkboxes ​​to the page A control checkbox that will act as a subject, notifying other checkboxes that should be checked One container for the new added checkboxes Next, we define the ConcreteSubject and ConcreteObserver handlers to add new observers to the page and implement the update interface. Below are built-in comments on what these components do in the context of our example. ______model taken from the book "Learning JavaScript Design Patterns - Addy Osmani 2012-2020."