🌱Aadam's Garden

Search

Search IconIcon to open search

Abstract Factory Pattern

Last updated Aug 15, 2022

Source:: Software Design Patterns - Best Practices for Software Developers


Definition

Defining an interface to create families of related or dependent objects without specifying their concrete classes.

An abstract factory can be thought of as a super factor or a factory of factories. The pattern achieves the creation of a family of products without revealing concrete classes to the client.

An Abstract Factory should be used where a system must be independent of the way the objects it creates are generated or it needs to work with multiple types of objects.

# Example

An example that is both simple and easier to understand is a vehicle factory, which defines ways to get or register vehicles types. The abstract factory can be named AbstractVehicleFactory. The Abstract factory will allow the definition of types of vehicle like “car” or “truck” and concrete factories will implement only classes that fulfill the vehicle contract (e.g. Vehicle.prototype.drive and Vehicle.prototype.breakDown).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

// ES2015+ keywords/syntax used: class, constructor, static, const

class AbstractVehicleFactory {
    constructor() {
        // Storage for our vehicle types
        this.types = {};
    }

    static getVehicle(type, customizations) {
        const Vehicle = this.types[type];

        return Vehicle ? new Vehicle(customizations) : null;
    }

    static registerVehicle(type, Vehicle) {
        const proto = Vehicle.prototype;

        // only register classes that fulfill the vehicle contract
        if (proto.drive && proto.breakDown) {
            this.types[type] = Vehicle;
        }

        return abstractVehicleFactory;
    }
}

// Usage:

abstractVehicleFactory.registerVehicle('car', Car);
abstractVehicleFactory.registerVehicle('truck', Truck);

// Instantiate a new car based on the abstract vehicle type
const car = abstractVehicleFactory.getVehicle('car', {
    color: 'lime green',
    state: 'like new',
});

// Instantiate a new truck in a similar manner
const truck = abstractVehicleFactory.getVehicle('truck', {
    wheelSize: 'medium',
    color: 'neon yellow',
});

# Resources