Creational Design Patterns Simplified

Creational Design Patterns Simplified

Creational design patterns? What are design patterns?

Design patterns are reusable code structures that software developers use to solve reoccurring problems or create new features. You can think of software design patterns as a way to code to solve common problems, or you can see them as software blueprints/templates for solving problems.

So, what is a Creational design pattern?

Ever thought of how to control how objects are created, the form they take and how they operate? Creational design patterns are there for just that. They control how objects are created and they give the object a form definition when instantiated. Creational design patterns are very common, and you can find them in almost every High-Level Programming Language examples are the Constructor design pattern, Factory design pattern, Singleton design pattern and Prototype design pattern.

The Constructor Design Pattern

This design pattern is the most common among all others, it is the default way most programmers create their objects. As the name suggests it is used to give objects constructs(attributes) and one feature of this design pattern is that it makes each instantiated object unique in attributed. The code snippet below is a Javascript class using the constructor pattern:

eg.jpg

The Factory Design Pattern

Factory Design Pattern as the name Factory suggests a place where products are manufactured in large quantities. The factory design pattern does the same thing it helps you instantiate different objects in large quantities without having to call the construct keyword. You can think of it as an object that manufactures objects. This code snippet below shows what a factory looks like:

class AnimalFactory{

    constructor(){
     //function to create animal class instances based on the type argument
        this.birthAnimal=function(name,type){
           if (type=="dog") {
            return new Dog(name)
           } else if(type=="cat") {
            return new cat(name)
           }
        }
    }
}

class Dog{
    constructor(name){
        this.name=name
        this.type="dog"
    }
}

class cat{
    constructor(name){
        this.name=name
        this.type="dog"
    }
}
//Creates a new instance of the AnimalFactory class
let Sparko=new AnimalFactory()

//Creates a new instance of the Dog class
let Bingo=Sparko.birthAnimal('Bino','dog')

console.log(Bingo) // returns Dog { name: 'Bino', type: 'dog' }

In the code snippet above you can see that we created three classes (AnimalFactory, Dog, and Cat). If you look at the AnimalFactory Class you would see that it was given the ability to create and return the Dog class and Cat Class based on the if-else conditional in its constructor. So, this is pretty much the Factory design pattern that looks like an object with the ability to create other objects.

The Singleton Design Pattern

This is another awesome creational design pattern commonly seen in centralized database systems. This design pattern focuses on making only one single object instance in other to keep the data stored in the object central and global. If you are familiar with Laravel you'll see that the $app object instance is a singleton.

class Database{
 constructor(){
  if(!Database.instance){
        this.data=[]
        Database.instance=this
       }
       return Database.instance
   }
}
} 


let singlet=new Database()
let newInstance=new Database()

console.log(singlet==newInstance)// Returns true

The reason why the singlet variable and the newInstance variable were the same is; in the singleton design pattern there can only be one object instance so if you try to create another instance the class returns the existing instance.

The Prototype Design Pattern

This is another awesome creational design pattern, and it is the method of inheritance Javascript uses rather than the classical object-oriented inheritance. So how the prototype design pattern works is that it gives objects the ability to be instantiated by copying the skeleton of an existing and functional object. The code snippet below shows a live example:

//Prototype
const dog={
    legs:4,
    bark: ()=>{
       return "bark"
    }
}

const bingo=Object.create(dog,{color:{value:"red"}})//the dog argument is the prototype
console.log(bingo.__proto__==dog)//Returns true
console.log(bingo.bark()) //Returns bark

The Builder Design Pattern

This is another interesting but unpopular creational design pattern; it is both hard and easy to implement. This design pattern works by gradually creating complex object instances, it is like a step-by-step process to initialize an object. For example, let's use the builder pattern to instantiate an animal object. So, we'll start with a baseline class called Animal.

class Animal{
    //All the baseline attributes
    constructor(name,color,age){
        this.name=name
        this.color=color
        this.age=age
    }
}

This is the first step we took, creating a base class; the next step we'll take is to create a class and name it AnimalBuilder, the purpose of this class is to help fill attributes into the base class Animal because it has too many attributes.

class Animal{
    //All the baseline attributes
    constructor(name,color,age){
        this.name=name
        this.color=color
        this.age=age

    }
}

class AnimalBuilder{
    //Builder Construct 
    constructor(name,color){
      this.name=name
      this.color=color
    }
    //A setter for the age attribute
    setAge(age){
        this.age=age
        return this
    }
   //The build function to instantiate the base class
   build(){
      return new Animal(this.name,this.color,this.age)
   }
}

let Ruit=new AnimalBuilder('Ruit','black')

//Set the animal's age and calls the build function
Ruit= Ruit.setAge(3).build()

console.log(Ruit)//returns Animal { name: 'Ruit', color: 'black', age: 3 }

If you look at the code snippet, you'll see that the AnimalBuilder class had a build() function that it used to instantiate the base class(Animal). This is simply how the builder design pattern works, unlike the constructor design pattern that instantiates and creates the class at once.

So these are the major creational design patterns that are widely used in different aspects of the digital world; the take-home advice from this article is that as a software developer never have only one way to implement solutions, always find another way to solve problems. Do not limit yourself! Thank you.