I usually strive to write maintainable, readable, and reusable code. Code structuring becomes more important as applications become larger. Design patterns prove crucial to solving this challenge — providing an organization structure for common issues in a particular circumstance.
The design patterns includes the following:
Each pattern consists of many properties, though, I will emphasize the following key points:
- Context: Where/under what circumstances is the pattern used?
- Problem: What are we trying to solve?
- Solution: How does using this pattern solve our proposed problem?
- Implementation: What does the implementation look like?
Module Design Pattern
Modules should be Immediately-Invoked-Function-Expressions (IIFE) to allow for private scopes — that is, a closure that protect variables and methods (however, it will return as an object instead of a function). This is what it looks like:
Here we instantiate the private variables and/or functions before returning our object that we want to return. Code outside of our closure is unable to access these private variables since it is not in the same scope.
REVEALING MODULE PATTERN
A variation of the module pattern is called the Revealing Module Pattern. The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks like this:
Although this looks much cleaner.
PROTOTYPE DESIGN PATTERN
Similar to Module pattern, the Prototype pattern also has a revealing variation. The Revealing Prototype Pattern provides encapsulation with public and private members since it returns an object literal.
Observer Design Pattern
There are many times when one part of the application changes, other parts needs to be updated. In AngularJS, if the $scope object updates, an event can be triggered to notify another component. The observer pattern incorporates just that — if an object is modified it broadcasts to dependent objects that a change has occurred.
A Singleton only allows for a single instantiation, but many instances of the same object. The Singleton restricts clients from creating multiple objects, after the first object created, it will return instances of itself.
Design patterns are frequently used in larger applications, though to understand where one might be advantageous over another, comes with practice.
Before building any application, you should thoroughly think about each actor and how they interact with one another. After reviewing the Module, Prototype, Observer, andSingleton design patterns, you should be able to identify these patterns and use them in the wild.
If you have any suggestions please let me know
Happy Coding :)