Factory Design Pattern - Javascript

Factory Design Pattern - Javascript

Factory Design Pattern

  • Factory design pattern is one of the creational design patterns.
  • Factory design pattern describes how the object should be created.
  • It is used to separate the object creation logic from the rest of our code.
  • It has only one responsibility. i.e. to create objects only based on the provided inputs.
  • It simplifies the object creation logic by having the object creation logic at one place.

When to use Factory Design Pattern

  • When we need to keep the object creation logic in one place.
  • To separate out the responsibility of object creation from the code which uses these objects.

Code example

  • The shape is one of the examples which we can use in our code example.
class Shape {
    constructor(description) {
        this.description = description;
    }
}

class shapeFactory {
    createShape(shapeType) {
        switch(shapeType) {
            case 'square':
                return new Shape('Square shape');
            case 'rectangle':
                return new Shape('Rectangle shape');
            case 'circle':
                return new Shape('Circle shape');
        }
    }
}

const factory = new shapeFactory();
const circle = factory.createShape('circle');
const square = factory.createShape('square');
const rectangle = factory.createShape('rectangle');

console.log(circle); // Shape {description: 'Circle shape'}
console.log(square); // Shape {description: 'Square shape'}
console.log(rectangle); // Shape {description: 'Rectangle shape'}
  • In this example, you can see that the shapeFactory is a factory class that creates shape objects based on the shapeType provided.
  • You can find the code in the GitHub repository.

One Last Thing...

  • If you'd like to stay in the loop of Software Development then please subscribe to my newsletter. I will try my best to keep you informed about the latest trends and best practices for Software Development.

  • Please like and follow the blog post. Connect with me on Twitter and LinkedIn.

Let me know in the comments what you will like to learn next... Thanks for visiting the blog...

Did you find this article valuable?

Support The Awesome Programmer by becoming a sponsor. Any amount is appreciated!