Javascript Design Pattern — Part 2

Deepak Rai
2 min readSep 30, 2021

In this article we will talk about creational design pattern.I will explain below three pattern under this.

Constructor Pattern

Factory Pattern

Singleton Pattern

  1. Constructor Pattern

This is very easy and straightforward pattern as this will help you to create instance of class/script/plugin

class Test {
constructor(firstname, lastname) {
// setting property values
this._firstname = firstname;
this._lastname = lastname;

// declaring a method on the object
this.getFullName = function() {
return `${this._firstname} ${this._lastname}`;
};
}

}

const testClassObj = new Test(‘Deepak’, ‘Rai’);

console.log(testClassObj.getFullName());

2. Factory Pattern

Factory design pattern works like a factory in the real world in that it creates something for others to use. In the context of OOPs, it helps in creating and instantiating objects.

class MySQLDB
{
public function setHost($host)
{
// code
}
public function setDB($db)
{
// code
}
public function setUserName($user)
{
// code
}
public function setPassword($pwd)
{
// code
}
public function connect()
{
// code
}
}

class PostgreSQLDB
{
public function setHost($host)
{
// code
}
public function setDB($db)
{
// code
}
public function setUserName($user)
{
// code
}
public function setPassword($pwd)
{
// code
}
public function connect()
{
// code
}
}

class DBFactory
{

setDriver(driver)
{
this.driver = driver;
}

makeDB(host, user, pass, dbname)
{
if (this.driver === ‘mysql’) {
DB = new MySQLDB();
}
else if (this.driver === ‘postgre’) {
DB = new PostgreSQLDB();
}
else if (this.driver === ‘sqlite’) {
DB = new SQLiteDB();
}

DB.setHost(host);
DB.setDB(dbname);
DB.setUserName(user);
DB.setPassword(pass);
DB.connect();

return DB;
}
}

dbFactory = new DBFactory;
dbFactory.setDriver(‘mysql’);
DB = dbFactory.makeDB(“host”, “db”, “user”, “pwd”);

3. Singleton Pattern

We use the singleton pattern in order to restrict the number of instances that can be created from a resource consuming class to only one.Resource consuming classes are classes that might slow down our website or cost money. For example:

Some external service providers (APIs) charge money per each use.
Some classes that detect mobile devices might slow down our website.
Establishing a connection with a database is time consuming and slows down our app.

class Test{

constructor(msg){

if(Test.Singleton){
return Test.Singleton;

}
this.msg = msg;
Test.Singleton = this;
return Test.Singleton;
}

}

let obj1 = new Test(‘First’)
let obj2 = new Test(‘Second’)

console.log(obj1)
console.log(obj2)

--

--