DEV Community

eidher
eidher

Posted on • Edited on

2 1

Factory Method Pattern

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Alt Text

Participants

  • Product: defines the interface of objects the factory method creates.
  • ConcreteProduct: implements the Product interface
  • Creator: declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. May call the factory method to create a Product object.
  • ConcreteCreator: overrides the factory method to return an instance of a ConcreteProduct.

Code

public class Main {

    public static void main(String[] args) {
        Creator[] creators = new Creator[2];

        creators[0] = new ConcreteCreatorA();
        creators[1] = new ConcreteCreatorB();

        for (Creator creator : creators) {
            Product product = creator.factoryMethod();
            System.out.println("Created " + product.getClass().getSimpleName());
        }

    }
}

public interface Product {

}

public class ConcreteProductA implements Product {

}

public class ConcreteProductB implements Product {

}

public interface Creator {

    Product factoryMethod();
}

public class ConcreteCreatorA implements Creator {

    @Override
    public Product factoryMethod() {
        return new ConcreteProductA();
    }
}

public class ConcreteCreatorB implements Creator {

    @Override
    public Product factoryMethod() {
        return new ConcreteProductB();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Created ConcreteProductA
Created ConcreteProductB
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay