Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
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(); } }
Output
Created ConcreteProductA Created ConcreteProductB
Top comments (0)