Come Sail Away with Design Patterns

The Factory Pattern

In continuation of my previous blogs on Design Patterns we come to the Factory pattern. As a quick reminder design patterns are solutions created for commonly found problems. The Factory pattern is a creational pattern meaning that it is a best practice for how to create an object. Let’s check it out.

The factory pattern objective is extensibility, expandable. It is often used in applications that manage, maintain, or manipulate collections of object that are different but also have many similar characteristics, i.e. methods, properties, modules. Document files can be used as an example like the mix of PDF, Word, Pages, GoogleDocs, etc.

The main components of your Factory are Creator, AbstractProduct, ConcreteProduct.

Creator — also known as the factory, the object that creates new products, it’s typically implemented as factoryMethod which returns newly created objects.

AbstractProduct — declares an interface to help create the objects. You typically won’t find this in JavaScript, but still an important piece to know about.

ConcreteProduct — the objects or products that are ultimately created, also all the objects or products support the same characteristics.

To explain the usefulness, let’s think about a factory with employees. You have Full Time, Part Time, Temp, and Contract workers. All of them share the same properties of work, functions, etc. However, maybe the Contract workers are part of a Union, maybe the amount that each group makes is different. So instead of trying to make a class with similar methods, you create an Employee class and allow for a property of type to be set to FT, PT, T, and C.

function Factory () {
this.createEmployee = function (type){
const employee

if(type == "FT"){
employee = new FullTime()
}
...
...
employee.type = type employee.hoursAllotted = function () {
log.add(this.type + "works for" + this.hours
}
return employee
}}const FullTime = function () {
this.hours = "40 hours"
}const Contractor = function () {
this.hours = "20 hours"
}

Now as you can see you change what kind of workers you have, allowing you to maintain similar classes without the difficulty of maintaining different classes.

Hope this insight helps your code in the future.