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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay