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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up