Factory Method Pattern


  

The Factory Method Pattern is a creational design pattern that provides an interface for creating objects in a parent class, but allows subclasses to change the specific type of object instantiated. This approach allows you to delegate the creation logic to a derived class, providing greater flexibility and maintainability of your code.

🔗 Do you like Techelopment? Check out the website for all the details!


Pattern Family: Creational Patterns

The Factory Method belongs to the family of creational design patterns, that is, those patterns that deal with the creation of objects in a controlled and flexible way. Unlike the direct creation of instances through the constructor (new), the Factory Method allows you to abstract the instantiation process and reduce the dependency on concrete classes.


Diagram




How the Pattern Factory Method Works

The Factory Method works by defining an abstract method in a base class and delegating the creation of the object to concrete subclasses.

Simple example

Let's imagine we have a hierarchy of Product objects and we want to create different types of products without directly depending on their concrete classes.

// Product interface
class Product {
    operation() {
        throw new Error("Method 'operation()' must be implemented.");
    }
}

// Concrete implementations
class ProductA extends Product {
    operation() {
        console.log("Operation of Product A");
    }
}

class ProductB extends Product {
    operation() {
        console.log("Operation of Product B");
    }
}

// Factory class
class Factory {
    static getFactory(type) {
        switch (type) {
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
            default:
                throw new Error("Unknown product type");
        }
    }
}

// Using the Factory Method
const product = Factory.getFactory("A");
product.operation();

This way, we can instantiate a product without directly knowing its concrete class.


A more concrete example

Let's imagine implementing a system to generate notifications in an application, where we have different types of notifications such as Email, SMS and Instant Messaging.

// Notification interface
class Notification {
    send(message) {
        throw new Error("Method 'send()' must be implemented.");
    }
}

// Concrete implementations
class EmailNotification extends Notification {
    send(message) {
        console.log("Sending Email: " + message);
    }
}

class SMSNotification extends Notification {
    send(message) {
        console.log("Sending SMS: " + message);
    }
}

class IMNotification extends Notification {
    send(message) {
        console.log("Sending instant message: " + message);
    }
}

// Factory class
class NotificationFactory {
    static getFactory(preference) {
        switch (preference) {
            case "EMAIL":
                return new EmailNotification();
            case "SMS":
                return new SMSNotification();
            case "IM":
                return new IMNotification();
            default:
                throw new Error("Unknown notification type");
        }
    }
}

// Using the Factory Method
const user = //... get user info
const notification = NotificationFactory.getFactory(user.notification_preference);
notification.send("Hello, this is a test message!");

In this way, thanks to the Factory Method pattern, we have decoupled the sending of the message from the type of communication medium chosen by the user. If the user were to change preference, the code would continue to work without the need for updates or revisions.

The Factory Method is a powerful tool to abstract the creation of objects and improve the maintainability of the code. By separating the instantiation logic from the concrete classes, it facilitates extensibility and reduces direct dependency on specific implementations. This pattern is particularly useful in scenarios where the type of object to be created varies based on the context or when the creation process is complex.



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment