Friday 22 May 2015

Design Patterns In JavaScript - Creational, Part 4


Prototype Pattern


Prototype pattern is one which creates objects based on a template of an existing object through cloning.

We can think of the prototype pattern as being based on prototypal inheritance where we create objects which act as prototypes for other objects. The prototype object itself is effectively used as a blueprint for each object the constructor creates.

One of the benefits of using the prototype pattern is that we're working with the prototypal strengths JavaScript has to offer natively rather than attempting to imitate features of other languages.

Not only is the pattern an easy way to implement inheritance, but it can also come with a performance boost as well, when defining a function in an object, they're all created by reference (so all child objects point to the same function) instead of creating their own individual copies.

We can use Object.create (introduced by ECMAScript 5, To remind ourselves, Object.create creates an object which has a specified prototype and optionally contains specified properties as well) for implement prototype pattern.

var vehicle = {
    model : "N/A",
    accelerate  : function(){
       console.log("accelerate");
    },
    wheelsNo : 4,
    getDriverName: function(){
       console.log("Driver: " + (this.driverName || "N/A"));
    }
};

var myCar = Object.create(vehicle);

var myFriendCar = Object.create(vehicle, {
    model : {
        value : "Ford"
    },
    doorsNo : {
        value : 2
    }, 
    driverName : {
        value : "Michael Philip"
    }
});

The above code we create our blueprint (vehicle) and use Object.create for create new object using it as a template, we can also suppose that we create a basic inheritance (vehicle) as a parent and myCar, myFriendCar are children.

We Create myCar object, and it clone every thing from parent, if we called getDriverName, it will log "N/A" because we not support it witj driverName and of course there is no model.

But myFriendCar object we create it also using Object.create, and we support it with some properties like doorsNo (not exist on parent object but a property for this object only) , and we support model property with value, also we set driverName Property with value, so if we call getDriverName method it will return "Michael Philip".

So, rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype or sample object. The Prototype pattern is also referred to as the Properties pattern.

Another example for classical implementation for prototype pattern a ClientBluePrint object that clones objects given a prototype object. Its constructor function accepts a prototype of type Client. Calling the clone method will generate a new Client object with its property values initialized with the prototype values.
var ClientPrototype = function (protoObj) {
    this.clone = function () {
        var client = new Client();
         
        client.first = protoObj.first;
        client.last = protoObj.last;
        client.status = protoObj.status;
         
        return client;
    };
 }
     
var Client = function(first, last) {     
    this.first = first;
    this.last = last;     
    this.say = function () {
        alert("Full Name: " + this.first + " " + this.last);
    };
}
     
var run = function() {
    var protoObj = new Client("Hamed", "Farag");
    var prototypeObj = new ClientPrototype(protoObj);
     
    var client = prototypeObj.clone();
    client.say();
}

run();

Tuesday 19 May 2015

Design Patterns In JavaScript - Creational, Part 1


mmmmm, The Design Patterns!

At this article we will talk about interesting topic, the design patterns and how to apply it using JavaScript.

So, What is the mean of design patterns?

In software development, a pattern (or design pattern) is a written document that describes a general solution to a design problem that recurs repeatedly in many projects.

Design patterns also provide us a common vocabulary to describe solutions. This can be significantly simpler than describing syntax and semantics when we're attempting to convey 
a way of structuring a solution in code form to others.

We Will Start With Creational Design Pattern In JavaScript,

Creational Design Patterns are focusing on how to create an objectBasically we can create an object by the following code and this way called Create Object Literal.

var obj = new Object();
var obj2 = {};

The Second Line is preferably because it less typing and less bits so will be transmit faster over the network. The Object will be more useful if we store data on it by using the properties. There are four ways to assign properties to an object.

     1. Use the dot syntax 
var obj = {};
obj.firstName = "Hamed";
obj.lastName = "Farag";

     2. We Can Use Square Brackets,
var obj = {};
obj["firstName"] = "Hamed";
obj["lastName"] = "Farag";
By using use square brackets, it give for us more flexibility,  for example we can use invalid keys or characters for JavaScript identifier.Also we can use space to create new property reserved keyword to create and assign property to an object.
var obj = {};
obj["first Name"] = "Hamed";
obj["last Name"] = "Farag";
obj["new"] = "new";
obj["true"] = "false";
but you typically don't to want do that, if you find yourself use a reserved keyword as a property name, you need to rethink what it is that you are actually doing.

    3. We Can Use Object.defineProperty Method, this introduce with ECMAScript 5 and it accept 3 arguments.
First argument is the object that we want to add to it a property, Second argument the name of property, last argument is a descriptor object for the property, it give a variety options for it (configurable, enumerable, value, writable, get and set).
For Example Value Option for set the value of this property.
var obj = {};
Object.defineProperty(obj,'firstName', {
   value : "Hamed"
});
Object.defineProperty(obj,'lastName', {
   value : "Farag"
});

     4. We Can use Object.defineProperties, define multiple properties on the object, take 2 arguments. First one the object we need to add properties to it. Second argument, is another object the contains multiple descriptor objects.

So, if you want to create properties with a lot of control like (configurable, enumerable, value, writable, get and set), we need to use Object.defineProperties and Object.definePropertybut if you want to create properties in silent value so two first ways we can use.
var obj = {};
Object.defineProperties(obj, {
    "firstName" : {
        value : "Hamed"
    },
    "lastName" : {
        value : "Farag"
    }
});


We Also sometime need to create an object and contains its data at one step , so it make sense to do everything inside the object literal.
var person = {
   firstName : 'Hamed',
   lastName : 'Farag'
};
ECMAScript 5 introduce a new method called Create, This method for create new object with the specified prototype object and properties.
var obj = Object.create(Object.prototype); // it equal to = {};
var obj2 = Object.create(obj.prototype, {
   name : {
      value : "name"
   },
   sayHello : {
      value : function(){
         alert('Hello, ' + this.name);
      }
   }
});

Object.create method is build a prototype chain, what i mean is that we can apply inheritance using Object.create.

Design Patterns In JavaScript - Creational, Part 2

Constructor Pattern

Another Way to create object in java script is by using constructor function, this is a special function call within the new keyword this also called constructor pattern. So constructors are used to create specific types of objects - both preparing the object for use and accepting arguments which a constructor can use to set the values of member properties and methods when the object is first created.

To distinguish constructor function from other normal function we make first letter an upper letter (readability concept nothing else).
function Person(firstName, lastName){
   // This refere to the object that we are creating
   this.firstName = firstName;
   this.lastName = lastName;
   // we need to create a method, technicality we don't have method in JavaScript
   // we have a property hat contain function object, but logically we have a method
   this.sayHello = function(){};
};

There is a little problem with this basic constructor pattern the sayName method. 
Because of every person object we create we will create a new function object and assign to sayName propertyAnd Also this result increase memory usage and store into the memoryAlso it introduce inheritance issue by define method inside the constructor.
So to solve this problem we can define our method on the prototype.
Every function object has a property call prototype but it really only use with constructor pattern.
Any property that you define on the prototype it share between all instances of the constructor function.


function Person(firstName, lastName){
   // This refere to the object that we are creating
   this.firstName = firstName;
   this.lastName = lastName;
};

Person.prototype.sayName = function(){
   alert("Hello, " + this.name);
};

Introduction To Module Pattern


Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.
 
By Default JavaScript lake of privacy and one of most important at OOP is the privacy, because we need to protect out code from outside world

var dom = {
    _counter: 0,
    generatedId : function(){
        return "customId" + this._counter++;
    },
    create: function(tagName, id){
        var el = document.createElement(tagName);
        el.id = id || this.generatedId();
        return el;
    }
};

The above code we can call _counter and set it with any value we need  although it suppose that it a private member.
So We need to apply privacy to our code, we can apply function of scope and closure. We will create new object using the basic module pattern to create it.
The basic module pattern uses an immediately invoked function and return object. this give us the ability to use the local scope of of the invoked function and emulate privacy and what it will return it will public for the world.
var dom = (function(){     
     var _counter = 0;
     function generatedId(){
          return "customId"  + _counter++;
     }
     function create(tagName, id){
          var el = document.createElement(tagName);
          el.id = id || generatedId();
          return el;
     }
     return {
          generatedId: generatedId,
          create: create
     };
})();
So at the above code, we just expose to the public our two methods only (generatedId and create) and the _counter will not access any more again from public.
Also By Useing module pattern we can mix in other objects, by passing what we need, for example the JQuery or another module as argument to the immediately invoked function.
var dom = (function(jq, logger){     
     var _counter = 0;
     function generatedId(){
          return "customId"  + _counter++;
     }
     function create(tagName, id){
          var el = document.createElement(tagName);
          el.id = id || generatedId();
          return el;
     }
     return {
          generatedId: generatedId,
          create: create
     };
})(JQuery, loggerModule);

Singleton Pattern

Singleton looks like a module pattern and easy to assume that singleton is module and module is singleton. but it is not the case because they have two different purpose. 
The purpose of module is cleanly separate unit of code. Singleton make sure that a class has only one instance and provide a global point of access to it
But of course we don't have class on JavaScript,so from JavaScript perspective, insure that object has only one instance and provide a global point of access to it.

So when we talk about singleton we not take about the single instance of object, we taking about the thing that insure that there only one instance of the object and provide access to that one instance.

var dom = (function(){     
     var _counter = 0;
     var instance;
     function generatedId(){
          return "customId"  + _counter++;
     }
     function create(tagName, id){
          var el = document.createElement(tagName);
          el.id = id || generatedId();
          return el;
     }
     function createInstance(){
          return {
             generatedId: generatedId,
             create: create
          };
     }

     return {
          getInstance: function(){
             return instance || (instance = createInstance());
          }
     };
})();
 The secret is of singleton is this line ( return instance || (instance = createInstance()); ).
It check for instance if has a value so return it else call createInstance() and assign what it is return to instance variable and that is happen at first time we call getInstance() method.

Design Patterns In JavaScript - Creational, Part 3

Factory Pattern


Factory Pattern we use to create objects, this object can be different types of objects but usually related in some way. for example they could share the same parent object or data type or they just have the same interface.

The Factory Method allows the client to delegate object creation while still retaining control over which type to instantiate.

The key objective of the Factory Method is extensibility. Factory Methods are frequently used in applications that manage, maintain, or manipulate collections of objects that are different but at the same time have many characteristics (i.e. methods and properties) in common.

Three 
objects should participating in this pattern are:
  • Creator: Factory:
    • The 'factory' object that creates new products implements 'factoryMethod' which returns newly created products.
  • Abstract Product :
    • Not used in JavaScript (The AbstractProduct not implemented because Javascript does not support abstract classes or interfaces. However, we still need to ensure that all employee types have the same interface (properties and methods)).
    • declares an interface for products
  • Concrete Product:
    • The product being created.
    • All products support the same interface (properties and methods)

We have an example like Employee factory, we have CEO, Project Manager, Team Leader, Software Enginner And Quality Software Engineer positions. Each one of them has his hourly rate.
  • Employee is the factory.
  • CEO, Project Manager, Team Leader, Software Beginner And Quality Software Engineer are the Concrete Products.

var log = (function () {
    var log = "";
 
    return {
        add: function (msg) { log += msg + "\n"; },
        show: function () { alert(log); log = ""; }
    }
})();

var EmployeeFactory = (function(log){

    var CEO = function () {
        this.hourly = "$100";
    };
 
    var ProjectManager = function () {
        this.hourly = "$80";
    };
 
    var TeamLeader = function () {
        this.hourly = "$65";
    };
 
    var SoftwareEnginner = function () {
        this.hourly = "$30";
    };

    var SoftwareQualityEnginner = function () {
        this.hourly = "$30";
    };

    var createEmployee = function(type){
        var employee;
 
        if (type === "CEO") {
            employee = new CEO();
        } else if (type === "ProjectManager") {
            employee = new ProjectManager();
        } else if (type === "TeamLeader") {
            employee = new TeamLeader();
        } else if (type === "SoftwareEnginner") {
            employee = new SoftwareEnginner();
        } else if (type === "SoftwareQualityEnginner") {
            employee = new SoftwareQualityEnginner();
        }
 
        employee.type = type;

        employee.say = function () {
            log.add(this.type + ": rate " + this.hourly + "/hour");
        }

        return employee;
    };


    return {
       createEmployee: createEmployee
    };
})(log);
 
 
var run = function() {
    var employees = [];

    employees.push(EmployeeFactory.createEmployee("CEO"));
    employees.push(EmployeeFactory.createEmployee("TeamLeader"));
    employees.push(EmployeeFactory.createEmployee("SoftwareEnginner"));
    employees.push(EmployeeFactory.createEmployee("SoftwareQualityEnginner"));
    
    for (var i = 0, len = employees.length; i < len; i++) {
        employees[i].say();
    }
 
    log.show();
}

run();
The core method of the above code is the createEmployee Method, check for type, if we need to apply specific business we will apply and return a new object to the user.