/ JavaScript

Proxy Design Pattern in JavaScript

Definition

A proxy is an object that has the same interface as another object and is used in place of that other object. It provides a surrogate or placeholder for another object to control access to it. It intends to add a wrapper and delegation to protect the real component from undue complexity.

The Proxy design pattern falls under the structural design patterns category.

Use cases

  • Delaying instantiation of resource-hungry objects where we do not want to instantiate then until the client requests them.
  • Accessing a remote object and provide a local representative of it.
  • Security reasons such as controlling access to a sensitive master object where the substitute object verify the caller access permissions before forwarding the request.

Example

This design pattern should be relatively simple and easy to grasp, so let's take an example. The comments in the code explain the intended functionality of each method.

let BankAccounts = function() {
    //constructor
};

BankAccounts.prototype = {
    add(bankAccountData) {
        // funtionality for adding a new bank account
    },
    find(bankAccount) {
        // searching the list of bank accounts
    },
    getList() {
        // return a list of all the bank accounts
    }
};

// creating the proxy
var BankAccountsProxy = function() {
    // getting a reference to the original object
    this.bankAccounts = new BankAccounts();
};

BankAccountsProxy.prototype = {
    addBankAccount(bankAccountData) {
        // some funtionality before calling the add method on BankAccounts
        return this.bankAccounts.add();
    },
    findBankAccount(bankAccount) {
        // some funtionality before calling the find method on BankAccounts
        return this.carList.find();
    },
    getBankAccountsList() {
        // some funtionality before calling the getList method on BankAccounts
        return this.carList.getList();
    }
};
Anas Shekhamis

Anas Shekhamis

A software engineer who specializes in architecting and developing web applications. On a daily basis, I use Python, JavaScript, Ruby, and PHP to design and implement API's and build web applications.

Read More
Proxy Design Pattern in JavaScript
Share this