DEV Community

Tommy
Tommy

Posted on

Factory Design Pattern

The Factory Design Pattern is a type of creational pattern. It lets you create objects without directly instantiating a specific class. Instead, it uses a factory to decide which object to create.

This pattern is useful for promoting loose coupling by delegating the responsibility of instantiating objects to the concrete factory class.

It is commonly used for creating objects based on specific types and conditions.

class Main {
    public static void main(String[] args) {
        ToyFactory toyFactory = new ToyFactory();

        // Create a Car toy
        Toy car = toyFactory.createToy("CAR");
        car.play();  // Output: Vroom! Car toy is moving.

        // Create a Doll toy
        Toy doll = toyFactory.createToy("DOLL");
        doll.play();  // Output: Hello! Doll toy is talking
    }
}

// Create a Toy interface
interface Toy {
    void play();
}

// Implement concrete Toy classes
class CarToy implements Toy {
    @Override
    public void play() {
        System.out.println("Vroom! Car toy is moving.");
    }
}

class DollToy implements Toy {
    @Override
    public void play() {
        System.out.println("Hello! Doll toy is talking.");
    }
}

// Create the ToyFactory class
class ToyFactory {
    // Factory method to create toys based on type
    public Toy createToy(String toyType) {
        if (toyType == null) {
            return null;
        }
        if (toyType.equalsIgnoreCase("CAR")) {
            return new CarToy();
        } else if (toyType.equalsIgnoreCase("DOLL")) {
            return new DollToy();
        }
        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)