introduction to design patterns in javascript
DESCRIPTION
This is a very basic introduction to implementing in design patterns in JS in order to properly organize and structure the code.TRANSCRIPT
![Page 1: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/1.jpg)
Santhosh KumarGithub.com/santhotech
An Introduction to Design Patterns
![Page 2: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/2.jpg)
What are Design Patterns
• Design Patterns provide the roadmap to implement solutions for various issues in software development
• A ready made solution that can be customized and reused
• A design pattern will make the code look self expressive by providing structure and semantics to the code
• They are not the final solution but a means to achieve the solution in an elegant manner
• Provides a common platform and reduces time required for transition
![Page 3: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/3.jpg)
Advantages
• Provides the ability to reuse code that can save a lot of time• It is a standard that developers are aware of hence improves
the understanding of code base new/old within a team• If used efficiently can help in reducing the overall footprint• Provides multiple platforms that doesn’t constraint the usage
or dictate the behaviour while maintaining the sanity of the system
• Helps in faster testing and implementation
![Page 4: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/4.jpg)
Design Pattern Categories
• Creational Design Patterns– Deals with the way a class and object instances are created
• Structural Design Patterns– Deals with maintaining structural integrity of the system by enforcing sane
relationships
• Behavioural Design Patterns– Helps in establishing communication between distinct parts of the system
(or) Object communication
![Page 5: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/5.jpg)
Creational Patterns
• Deals with Object creation mechanism and class creation mechanism
• Provides a way for object creation depending on the changing scenarios
• Reduces duplication in terms of instantiation• Reduces memory over head in dealing with multiple objects of
the same type• Ex: Constructor, Factory, Abstract, Prototype, Singleton, Builder
etc
![Page 6: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/6.jpg)
Structural Design Pattern
• Provides a set of protocols on structuring the components of the system
• Helps in reducing/decoupling the structural dependencies with in a system
• Provides a means to create independent structures that can maintain their own state
• Helps in restructuring the components of the system which doesn’t have a common purpose
• Ex: Decorator, Façade, Adapter, Proxy etc
![Page 7: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/7.jpg)
Behavioural Design Pattern
• Focuses on streamlining the communication between the objects in the system
• Helps in establishing a common set of protocols to pass data and keep objects in sync
• Provides a means to ensure reactive implementation of objects irrespective of their state
• Ensures that communication happens through as less channels as possible to ensure maintainability
• Ex: Iterator, Mediator, Chain of Command, Observer, Visitor etc
![Page 8: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/8.jpg)
Design Patterns in OO Javascript
• JavaScript is a Pseudo class based language – Functions are manipulated to simulate a class based environment
• All JS objects are inherited from “Object” using a base constructor
• All constructors gets a prototype object• All default properties of an object is assigned in the prototype• Each individual object consists of its own prototype which
inherits from the parent
![Page 9: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/9.jpg)
Constructor pattern
• Creational Design Pattern• Javascript objects can be created by• var obj = {}; • var obj = Object.create(Object.prototype);• Var obj = new Object();• Any call to a function is actually a call to a constructor method of the
same function since functions behaves like classes in javascripts• Adding a “new” to a constructor makes it return a empty instance (if
passed without parameters) of the object the constructor points to
![Page 10: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/10.jpg)
Cont…
function Animal(name, class) { this.name = name; this.class = class; this.getName = function() { return “Name :”+this.name; }
Var a1 = new Animal(“lion”, “predator”);Var a2 = new Animal(“Tiger”, “predator”);
![Page 11: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/11.jpg)
Cont…
• All common methods can be grouped in a single wrapper• “this” refers to the current object inside the constructor
function• Not ideal as inheritance cannot be implemented directly –
scope of “this” referring to the methods will result in a conflict• Methods referenced with this gets redefined for every instance
that is created – end up with 100 “getName” definitions if there are 100 animals
![Page 12: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/12.jpg)
• JS consists of a prototype property that is available for all functions
• Any number of methods and properties can be attached to the prototype property of the function
• When constructor is called to create new object the properties attached to prototype of the constructor is automatically available to the new object
• The “this” keyword inside a property attached to prototype will still refer to the current object
![Page 13: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/13.jpg)
function Animal(name, class) { this.name = name; this.class = class;}Animal.prototype.getName = function() { return “Name :”+this.name; }
Var a1 = new Animal(“lion”, “predator”);Var a2 = new Animal(“Tiger”, “predator”);
![Page 14: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/14.jpg)
Usage/Merits/Demerits
• Ideal for wrapping up related and group able properties within an object container
• Can be used where ever a fundamental level of abstraction is required
• Provides a very easy implementation of inheritance and prototypal inheritance
• Doesn’t provide a direct mechanism to contain private members
![Page 15: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/15.jpg)
Object Literal Pattern
• Another Creational Design Pattern• Not the usual means to “instantiate” an object• Provides a way to group related behaviour usually in terms of a
page/UI component
![Page 16: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/16.jpg)
Var gridComponent = { settings: { gridColor: “#ff0000”, gridTitle: “My Title” }, init: function{ if (settings && settings(settings) == 'object') { $.extend(gridComponent.settings, settings); } gridComponent.bindEvents(); } bindEvents: function() { $(“#btn”).on(“click”, function() { gridComponent.onButtonClick(); }); $(“#drp”).on(“change”, function() { gridComponent.onDrpChange(); }); }}
![Page 17: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/17.jpg)
Usage/Merits/Demerits
• Can be used especially when dealing with third party libraries like Jquery to group common behaviour
• Instead of spaghetti calling methods of same component just a online initiation replaces all other calls
• Code may be longer than other forms of implementation• But the grouping helps in maintainability• Doesn’t provide private members
![Page 18: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/18.jpg)
Modular Pattern
• Provides the ability to effect namespacing• Allows creation of private members• Expose only certain logic that needs to be used by other parts
of the system• Helps to keep the global namespace clean and free of pollution
from the method variables
![Page 19: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/19.jpg)
Var Chart = (function(){ var chartWidth = 100; var chartHeight = 100; getAxis = function(param) { return Math.round(rand(param,2)); } return { generateChart: function(chartParam) { return getAxis(chartParam); } }})();
![Page 20: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/20.jpg)
Usage/Merits/Demerits
• Can be used where private members are required to keep the namespace clean and avoid naming conflicts which is also the advantage of using this pattern
• The private methods cannot be extended since their visibility is shielded
• Objects added later to the chain does not have access to the private members
• Private members cannot be unit tested
![Page 21: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/21.jpg)
Revealing Module Pattern
• A Slight variation of the modular pattern• In module pattern public methods need to address one another
along with the name of module• Revealing module pattern addresses this by returning an object
with references to the methods that are public and keeping all methods private by default
![Page 22: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/22.jpg)
var Chart = (function(){ var chartX = 0; var chartY = 0; function manipulate() { } function manipulateXY() { return manipulate(); } function generateChart(param) { return manipulateXY(); } return { getChart: generateChart };})();
Chart.getChart(param);
![Page 23: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/23.jpg)
Usage/Merits/Demerits
• Syntax is much cleaner as the return object clearly specifies what are returned hence establishing what are public
• Pattern is flexible enough only for public methods and not for public members
• Does not play well with inheritance as the public methods returned cannot be overridden since only reference is returned
![Page 24: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/24.jpg)
Singleton Pattern
• Restricts the instantiation of a class to just once such that it returns the same instance whenever and wherever it is requested from
• Singletons in JS returns a structure rather than returning an object or more precisely a reference to an object
![Page 25: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/25.jpg)
Var Helper = (function(){ var helperInstance; function init() { function domHelperPvt() { } var domHelperPvtProp = 0; return { domHelperPub: function () { }, domHelperPubProp: 1 }; }; return { getHelperInstance: function () { if ( !helperInstance) { helperInstance = init(); } return helperInstance; } };})();
Var helper = Helper.getHelperInstance();Helper.domHelperPub();
![Page 26: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/26.jpg)
Usage/Merits/Demerits
• Used to create static instance like behaviour for accessing methods that are common across a wide range of components in a system
• Reduces memory overhead and helps in sane garbage collection
• Too many singletons will result in application being tightly coupled, hence reduce the performance and also maintainability
![Page 27: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/27.jpg)
Factory Pattern
• Provides a platform to provide objects that may be required frequently from time to time and also used by multiple components
• Not restricted to one instance but may not necessarily create new instance if the existing one can be reused
• Also a creational pattern
![Page 28: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/28.jpg)
Function DomFactory { this.createNewDom = function(domtype,param) { var newDom; if(domType===“chart”) { newDom = new Chart(param); } if(domType===“grid”) { newDom = new Grid(param); } return newDom; }}
DomFactory.createNewDom(“chart”,param);
![Page 29: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/29.jpg)
Usage/Merits/Demerits
• Useful when the calling client may need different objects depending on the scenario and such clients exist across the system
• Reduces the logical overhead in the client requesting for the object and moves common logic to a common wrapper that can be reused as necessary
• Cannot be used when there is no common behaviour between the objects returned
![Page 30: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/30.jpg)
Proto Patterns
• Patterns can be created within a team depending on what the team feels is efficient while maintaining the common rules that a pattern should adhere to
• A Pattern created within a team which can evolve over a period of time to represent something that is achieved through it
• Proto Patterns will evolve to be design patterns when it is widely accepted by the community
• Ex: Revealing Module Pattern
![Page 31: Introduction to Design Patterns in Javascript](https://reader033.vdocuments.site/reader033/viewer/2022061203/547da96cb4af9f18128b4700/html5/thumbnails/31.jpg)
Thank You