DEV Community

Cover image for Implementing a Simple Factory Pattern in JavaScript
teaganga
teaganga

Posted on

Implementing a Simple Factory Pattern in JavaScript

I'm currently implementing simple factory design pattern to create DOM controls. I'm trying to follow the SOLID design principles and design patterns and in general good practices. I implement the factory pattern as a simple 'class'(I'm using ecma5 style, so I don't know if I should call it a class) to instantiate DOM elements/controls and add them to the DOM.

function DomFactory(){

  // this is the create method
  this.create = (key, type, props, defaultVals) => {

    if (type === 'checkbox')
      return this.createCheckbox( key, props, defaultVals )

  }

  // creates a checkbox identified by key
  // using label as label
  this.createCheckbox = (key, props, defaultVals) => {

    const checkbox = document.createElement('input');
    let label = (props && props.label) || key;

    checkbox.type = 'checkbox';
    checkbox.id = 'ctrl-' + key;
    checkbox.name = checkbox.id;

    // Set the checkbox as checked if defaultVals is true
    if (defaultVals === true) {
      checkbox.checked = true;
    }    

    const labelElement = document.createElement('label');
    labelElement.htmlFor = checkbox.name;
    labelElement.appendChild(document.createTextNode(label));

    return { checkbox, labelElement };
  }

}
Enter fullscreen mode Exit fullscreen mode

As I'm just getting started with this piece of code, I'm going to add some more elements(for creating different types of controls) and to add more styles.

So I'm looking further to see if I should still use a factory pattern or maybe I should use a builder pattern or something related to a composite pattern, for instantiating recursive structures(like forms, panels or other elements containing child elements).

In the next post I'll show how I'm going to use a decorator pattern to add styles to the created elements, but separating concerns, since the factory deals with the creation of objects as a creational pattern, while the decorator is a structural pattern.

Using a decorator pattern seems a good idea also from the perspective of adhering to good practices and following SOLID design principles.

  • First of all following Single Responsibility Principle as described above. Or separation of concerns, but I think this is a more broader term.
  • Second of all, following Open Closed Principles for adding new functionality to an object (in this case, styling to the controls) without modifying the existing code of that object. The Controls class remains unchanged, and new functionality (styles) is added by wrapping the controls with additional behavior in the decorator.
  • Last but not least, it allows the use of Dependency Inversion Principle (DIP), by injecting decorators to get different types of elements(like using bootstrap styles or other types of styles, without changing the main functionality).

Top comments (0)