3 JavaScript Patterns you could start using in your next project

Alexey Olkhovoy
Ace for Engineering Leaders
3 min readJul 5, 2019

When you start with coding, you don’t need patterns, but you use them.

With the complexity of programs you create, it becomes inevitable, that without patterns you application will rather stop working at all or would become very unpredictable.

I decided to choose 3 JavaScript patterns and tell you it’s useful. Enjoy.

Pattern 1. Factories

Factory offers a generic object creation functionality where the type of factory objects to be generated can be specified.

Consequently, we only specify the object and instantiate the factory and return it for us to use.

Example:

// seller ASellerA = {};SellerA.title = function title() {
return "Seller A";
};
SellerA.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()}`;
};
//seller BSellerB = {};
SellerB.title = function title() {
return "Seller B";
};
SellerB.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()}`;
};
//@param {*} sellerOption
//@param {*} config
function sellerFactory(sellerOption, config = {}) {
const seller = Object.create(sellerOption);
Object.assign(seller, config);
return seller;
}
const sellerFactory = sellerFactory(SellerA, {
username: "user",
password: "pass"
});
console.log(sellerFactory.title());
console.log(sellerFactory.pay(12));
const sellerFactory2 = sellerFactory(SellerB, {
username: "user2",
password: "pass2"
});
console.log(sellerFactory2.title());
console.log(sellerFactory2.pay(50));

Pattern 2. Observers

The model of observer design is useful when objects interact concurrently with other objects.

There is no unnecessary push and pull of events throughout the states in this observer pattern, but the modules involved only change the current data status.

Example:

function Observer() {
this.observerContainer = [];
}
Observer.prototype.subscribe = function (element) {
this.observerContainer.push(element);
}
// The following removes the container componentObserver.prototype.unsubscribe = function (element) {const elementIndex = this.observerContainer.indexOf(element);
if (elementIndex > -1) {
this.observerContainer.splice(elementIndex, 1);
}
}
/* We notify items added to the container by calling * every component added to our container */
Observer.prototype.notifyAll = function (element) {
this.observerContainer.forEach(function (observerElement) {
observerElement(element);
});
}

Pattern 3. Singleton

It is crucial in a situation in which, only one instance needs to be established, for example, a database connection.

This pattern is also referred to as a specific pattern, one drawback related to this pattern is its daunting testing experience due to its hidden objects of dependencies that are not easily detected for testing.

When to Use:

  • Only when the connection closed an instance could be created.
  • Or when you want to ensure that the open instance is closed before opening a new one.

Example:

function DbConnection () {let dbInstance = null;// Tracks the number of instances at a given time
let count = 0;
function init() {
console.log(`Opening database #${count + 1}`);
//start operation
}
function createIntance() {
if(dbInstance == null) {
dbInstance = init();
}
return dbInstance;
}
function closeIntance() {
console.log('closing database');
dbInstance = null;
}
return {
open: createIntance,
close: closeIntance
}
}
const db = DatabseConnection();
db.open(); //Open db #1
db.open(); //Open db #1
db.open(); //Open db #1
db.close(); //close database

--

--

Alexey Olkhovoy
Ace for Engineering Leaders

CTO @Vectorly. Help teams make learning part of the workflow. Angular, React, Node.js