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 :)




要查看或添加评论,请登录

社区洞察

其他会员也浏览了