Providing a static method encapsulated in a class called the factory, to hide the implementation logic and make client code focus on usage rather than initializing new objects.
Real-world example
Imagine an alchemist who is about to manufacture coins. The alchemist must be able to create both gold and copper coins and switching between them must be possible without modifying the existing source code. The factory pattern makes it possible by providing a static construction method which can be called with relevant parameters.
Wikipedia says
Factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class.
Programmatic Example
We have an interface Coin
and two implementations GoldCoin
and CopperCoin
.
1public interface Coin {
2 String getDescription();
3}
4
5public class GoldCoin implements Coin {
6
7 static final String DESCRIPTION = "This is a gold coin.";
8
9 @Override
10 public String getDescription() {
11 return DESCRIPTION;
12 }
13}
14
15public class CopperCoin implements Coin {
16
17 static final String DESCRIPTION = "This is a copper coin.";
18
19 @Override
20 public String getDescription() {
21 return DESCRIPTION;
22 }
23}
Enumeration above represents types of coins that we support (GoldCoin
and CopperCoin
).
1@RequiredArgsConstructor
2@Getter
3public enum CoinType {
4
5 COPPER(CopperCoin::new),
6 GOLD(GoldCoin::new);
7
8 private final Supplier<Coin> constructor;
9}
Then we have the static method getCoin
to create coin objects encapsulated in the factory class
CoinFactory
.
1public class CoinFactory {
2
3 public static Coin getCoin(CoinType type) {
4 return type.getConstructor().get();
5 }
6}
Now on the client code we can create different types of coins using the factory class.
1LOGGER.info("The alchemist begins his work.");
2var coin1 = CoinFactory.getCoin(CoinType.COPPER);
3var coin2 = CoinFactory.getCoin(CoinType.GOLD);
4LOGGER.info(coin1.getDescription());
5LOGGER.info(coin2.getDescription());
Program output:
1The alchemist begins his work.
2This is a copper coin.
3This is a gold coin.
Use the factory pattern when you only care about the creation of a object, not how to create and manage it.
Pros
Cons