Skip to main content

Factory Pattern

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

~ Refactoring Guru

Factory Pattern UML Class Diagram

The Factory Method pattern allows subclasses to alter the type of objects created by a superclass, promoting flexibility and decoupling. It involves a creator class with a factory method that returns products, which must follow a common interface. Concrete creators override the factory method to return different product types, enabling the client code to treat all products interchangeably.

The Factory Method pattern creates objects through a factory method, allowing for loose coupling and easy extension. It enables the creation of new product types without modifying existing client code. The pattern can be used to reuse existing objects, saving system resources.

Prototype avoids inheritance drawbacks but requires complex initialization, while Factory Method, a Template Method specialization, eliminates initialization.

Slides

Factory Pattern
full screen click here

Step by Step Implementation

In this tutorial, we’ll use the Factory Method pattern to create different types of buttons based on themes (e.g., round and square buttons). Each button follows the same interface to ensure they share a common structure, but each type has its own unique style.

Let’s begin by creating a Button interface with methods that all button types should implement. This will serve as our base interface.

Live Editor
    function ButtonDemo() {
    // Button interface with a render method
        class Button {
            render() {
                throw new Error("Method 'render()' must be implemented.");
            }
        }
    // Testing the interface
    const button = new Button();
    return <div>{button.render()}</div>; // This should throw an error since render isn't implemented.
}
Result
Loading...