DEV Community

Cover image for Factory Design Pattern: #2
Israel-Lopes
Israel-Lopes

Posted on

Factory Design Pattern: #2

// Interface Product
public interface Product {
    void doSomething();
}

// ConcreteProductA implementation class
public class ConcreteProductA implements Product {
    @Override
    public void doSomething() {
        System.out.println("Doing something in ConcreteProductA");
    }
}

// ConcreteProductB implementation class
public class ConcreteProductB implements Product {
    @Override
    public void doSomething() {
        System.out.println("Doing something in ConcreteProductB");
    }
}

// Classe Factory
public class ProductFactory {
    public static Product createProduct(String type) {
        if (type.equalsIgnoreCase("A")) {
            return new ConcreteProductA();
        } else if (type.equalsIgnoreCase("B")) {
            return new ConcreteProductB();
        }
        throw new IllegalArgumentException("Invalid product type: " + type);
    }
}

public class Main {
    public static void main(String[] args) {
        Product productA = ProductFactory.createProduct("A");
        productA.doSomething();

        Product productB = ProductFactory.createProduct("B");
        productB.doSomething();
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have a Factory pattern that allows us to create different types of products (Product) using a factory (ProductFactory).

The Product interface defines common behavior for all products. Next, we have the ConcreteProductA and ConcreteProductB classes that implement the Product interface with specific behaviors.

The ProductFactory class is the factory responsible for creating product instances. It has a static method createProduct() that receives a type parameter indicating the desired product type. Based on that type, the factory instantiates and returns an object of the correct type. In the example, we have the creation of ConcreteProductA for type "A" and ConcreteProductB for type "B".

Finally, in the main() method of the Main class, we demonstrate how to use the factory to create the desired products. We create a product A with ProductFactory.createProduct("A") and a product B with ProductFactory.createProduct("B"). Next, we call the doSomething() method on each product, which performs each product's specific behavior.

The Factory pattern is useful when you need to create objects of different related classes, but only know the required object type at runtime. The factory abstracts object creation, allowing you to work with the common interface (Product) instead of specific implementations. This makes the code more flexible and makes it easier to add new product types in the future.

____________________<< go to back__________________

Texto alternativo da imagem

Top comments (0)