Mark As Completed Discussion

Factory

The Factory pattern helps create an instance of an object without exposing the instantiation logic to the code that needs the object. It's best used with objects that are not trivial to create.

Normally, when you create an object, you just call a class constructor directly:

1// In JavaScript
2const myObject = new MyObject();

Most of the time, there's nothing wrong with creating objects via constructors. However, sometimes you may want to make the parts of your code that need objects independent from the implementation of these objects. That's when Factory can help.

When using Factory, you don't call a constructor. Instead, you call a method in a static factory class and provide information about the type of object that you need. The factory returns an instance of the object you're looking for.

Here's a sample where you have a class representing a tennis ball and a static class for a factory that delivers a tennis ball:

1class ITennisBall {
2    getDiameter() {};
3    getMake() {};
4}
5
6class GrassCourtTennisBall extends ITennisBall {
7    constructor() {
8        super();
9        this.color = "Optic yellow";
10        this.diameter = 67;
11        this.bounce = 145;
12        this.make = "Slazenger Wimbledon";
13    }
14
15    getDiameter() { return this.diameter; }
16    getMake() { return this.make; }
17}
18
19const TennisBallFactory = {
20    deliverBall: function() { return new GrassCourtTennisBall(); }
21}

At call site, instead of calling a constructor for TennisBall, you use TennisBallFactory to deliver the ball:

1let ball = TennisBallFactory.deliverBall();
2console.log(`This is a ${ball.getMake()} ball with a diameter of ${ball.getDiameter()} mm`);

This is a simplified version of the Factory Method pattern. Another related pattern is Abstract Factory.