DEV Community

Bvnkumar
Bvnkumar

Posted on • Edited on

1

Javascript Factory Design Pattern

Design patterns are templates or solutions for common software development problems.

Design patterns are divided into three categories.

  1. Behavioral
  2. Creational
  3. Structural

The factory pattern is a creational design pattern that provides a generic interface for creating objects.

EX:-

function Developer(name , experience) {
    this.name = name;
    this.type = "Developer";
    this.experience = experience;
}
function Tester(name, experience) {
    this.name = name;
    this.type = "Tester";
    this.experience = experience;
}
function EmployeeFactory() {
    this.create = (name, type) => {
        switch (type) {
            case 1:
                return new Developer(name,4);
                break;
            case 2:
                return new Tester(name,6);
                break;
        }
    }
}

function say() {
    console.log("i am " + this.name + " i am a " + this.type +" and having a "+ this.experience +"years of experience ");
}

let employees = [];
const employeeFactory = new EmployeeFactory();
employees.push(employeeFactory.create("Sam", 1));
employees.forEach((employee) => {
    say.call(employee);
});
Enter fullscreen mode Exit fullscreen mode

As you can see, we have created developer and Tester objects with their names. Using this pattern you could create as many objects you require each with their own name and experience.

Image of Datadog

Learn how to monitor AWS container environments at scale

In this eBook, Datadog and AWS share insights into the changing state of containers in the cloud and explore why orchestration technologies are an essential part of managing ever-changing containerized workloads.

Download the eBook

Top comments (1)

Collapse
 
ant_f_dev profile image
Anthony Fung

Nice summary. The example's a little hard to read though; you can create a code block by typing three back-ticks on the lines above and below your code.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up