JavaScript Design Pattern

JavaScript Design Pattern

History of Design Pattern

Programming patterns have been around ever since they were created. But they were not formalized until 1994 when an influential textbook called "Design Patterns: Elements Of Reusable Object-Oriented Software" was released. This book was written by four composers - Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides - which became known as the Gang of Four (GoF).

What is a Design Pattern?

As the name implies, a pattern is a way to solve a common software problem - or in our case, writing JavaScript web applications. Another way to think of patterns is as templates for figuring out how to solve problems - ones that can be used in quite a few different circumstances.

Now, if you are wondering how a pattern is discovered, it's easy. When the same solution is repeated over and over again, someone will recognize it, name it, and then describe it in detail. A pattern is discovered in that way. They weren't forged overnight.

23 design patterns in three categories

There are 23 object-oriented design patterns. Since then, the "pattern approach" has become popular in the software engineering industry, and dozens of more patterns have been discovered since.

No alt text provided for this image

Three categories of design patterns are distinguished, as follows:

Creational Design Patterns

  1. Abstract Factory - Creates an instance of several families of classes.
  2. Builder - Separates object construction from its representation
  3. Factory Method - Creates an instance of several derived classes
  4. Prototype - A fully initialized instance to be copied or cloned
  5.  Singleton - A class of which only a single instance can exist

Structural Design Patterns

  1. Adapter - Match interfaces of different classes
  2. Bridge - Separates an object’s interface from its implementation
  3. Composite - A tree structure of simple and composite objects
  4.  Decorator - Add responsibilities to objects dynamically
  5.  Facade - A single class that represents an entire subsystem
  6.  Flyweight - A fine-grained instance used for efficient sharing
  7. Proxy - An object representing another object

Behavioral Design Patterns

  1. Chain of Responsibility - A way of passing a request between a chain of objects
  2.  Command - Encapsulate a command request as an object
  3.  Interpreter - A way to include language elements in a program
  4.  Iterator - Sequentially access the elements of a collection
  5.  Mediator - Defines simplified communication between classes
  6.  Memento - Capture and restore an object's internal state
  7.  Observer - A way of notifying change to a number of classes
  8.  State - Alter an object's behavior when its state changes
  9.  Strategy - Encapsulates an algorithm inside a class
  10.  Template Method - Defer the exact steps of an algorithm to a subclass
  11.  Visitor - Defines a new operation to a class without change

Javascript's most common design patterns

Prototype Design pattern: A prototype pattern is based on prototypical inheritance, where objects are built to be prototypes for other objects. As a matter of fact, prototypes serve as blueprints for the objects built by constructors.


var var myCar= {

    name:"Ford",
  
    brake:function(){
  
      console.log("Stop! I am applying brakes");
  
    },

    Panic : function (){
  
      console.log ( "wait. how do you stop thuis thing?")
  
    }
}

var yourCar= object.create(myCar);

console.log (yourCar.name);
          

Singleton Design Pattern: It is essential when one instance of an object is needed, for example, when a database connection is necessary. A new instance can only be created when the connection is closed or you close the existing instance before opening a new one. This pattern is also known as the strict pattern, one disadvantage is that it is difficult to test due to its hidden dependencies that cannot easily be isolated.


function DatabaseConnection () {

  let databaseInstance = null;
  
  let count = 0;
  
  
  function init() {

  console.log(`Opening database #${count + 1}`);

  }
  
  function createIntance() {
  
    if(databaseInstance == null) {
  
      databaseInstance = init();
  
    }
    
    return databaseInstance;
  
  }
   
  function closeIntance() {
  
      console.log('closing database');
  
      databaseInstance = null;
  
  }
  
  return {
  
      open: createIntance,
  
      close: closeIntance
  }
  
}
      
const database = DatabseConnection();

database.open(); 

database.open();

database.open(); 

database.close(); 
    
              

Factory Design Pattern: It is a creational concerned with the creation of objects without the need for a constructor. It provides a generic interface for creating objects, where we can specify the type of factory objects to be created. The factory, therefore, creates and returns the object for us to use after we specify the object. The factory pattern is useful when the object component set up is highly complex and when we need to create multiple instances of an object depending on the environment. Additionally, factory patterns can be used when working with many small objects that share the same properties and when composing objects that need to be decoupled.


DealerA = {};


DealerA.title = function title() {

    return "Dealer A";

};
    
    
DealerA.pay = function pay(amount) {

    console.log(
    `set up configuration using username: ${this.username} and password: ${
    this.password
    }`
    );

    return `Payment for service ${amount} is successful using ${this.title()}`;
    
};
    

DealerB = {};
    
DealerB.title = function title() {

    return "Dealer B";
    
};
    
    
DealerB.pay = function pay(amount) {

    console.log(
    `set up configuration using username: ${this.username}
    and password: ${this.password}`
    );

    return `Payment for service ${amount} is successful using ${this.title()}`;
    
};
    
    
function DealerFactory(DealerOption, config = {}) {

    const dealer = Object.create(dealerOption);

    Object.assign(dealer, config);

    return dealer;
    
}
    
    
const dealerFactory = DealerFactory(DealerA, {
    username: "user",
    password: "pass"
});

console.log(dealerFactory.title());

console.log(dealerFactory.pay(12));
    
    
const dealerFactory2 = DealerFactory(DealerB, {
    username: "user2",
    password: "pass2"
});
    
console.log(dealerFactory2.title());
    
console.log(dealerFactory2.pay(50));
    
  
            
Happy codding :)




To view or add a comment, sign in

More articles by OMKESH B. KENDRE 👋

  • Clipboard API in JavaScript

    The Clipboard API in JavaScript provides a convenient way to copy content to the user's clipboard, enabling seamless…

  • Unlocking Seamless Asynchronous Loading with React Suspense

    As web applications become more dynamic, the need for efficient data fetching and seamless user experiences has never…

  • Javascript Design Patterns

    JavaScript is a versatile and powerful programming language commonly used for web development. As applications become…

  • Polyfills for forEach()

    What is Polyfill? Polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect…

  • Polyfills for filter()

    What is Polyfill? Polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect…

  • Polyfills for map()

    What is Polyfill? Polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect…

  • Storybook

    Storybook is an open-source UI expert tool to build UI components and pages. It is easy to test UI components during…

  • Web Content Accessibility

    What is Web Accessibility? The web and internet is a most important part of our life which includes government…

    1 Comment
  • NVM - Node version manager

    NVM (Node Version Manager by the user creationix on GitHub) is a tool that allows the user to switch between different…

Others also viewed

Explore content categories