java factory method pattern
This post was migrated from Tistory. You can find the original here.
Factory Method
Instead of creating a Product object directly, a Factory class creates the Product for you.
There are multiple Product implementations, and corresponding Factory implementations that create each of them.
Each Factory implementation is responsible for creating its matching Product object.
The steps and methods needed to create an object are organized like a template,
while the internal behavior of those steps and methods can be flexibly customized in the Product and Factory implementations.
Advantages
Avoids tight coupling between the constructor and the concrete implementation object.
Through the factory method, you can specify common work to be performed after an object is created.
Encapsulation and abstraction hide the concrete type of the object being created.
Follows both SRP (Single Responsibility Principle) and OCP (Open Closed Principle).
Disadvantages
Since a factory class is created for each implementation, the number of subclasses grows very large.
Example
Abstract Product and its implementation
Abstract Factory and its implementation
1
2
3
4
5
6
7
8
9
10
11
12
public abstract class Bread {
BreadResult breadResult = new BreadResult();
@Override
public String toString() {
....
}
public abstract void setType();
public abstract void setRecipe();
}
1
2
3
4
5
6
7
8
9
10
public abstract class BreadFactory {
public Bread newBread() {
Bread bread = this.creatBread();
bread.setType();
bread.setRecipe();
return bread;
}
abstract Bread creatBread();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ButterBread extends Bread {
@Override
public void setType() {
super.breadResult.breadType = "butter";
}
@Override
public void setRecipe() {
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
...
super.breadResult.recipe = map;
}
}
1
2
3
4
5
6
public class ButterBreadFactory extends BreadFactory {
@Override
Bread creatBread() {
return new ButterBread();
}
}
References
https://gdtbgl93.tistory.com/19
[[Design Pattern] Factory Method Pattern
The Factory method pattern is an object-oriented design pattern. The Factory method is a pattern in which a parent (superclass) creates a concrete class it doesn’t know about, and the child (subclass) determines which object
gdtbgl93.tistory.com](https://gdtbgl93.tistory.com/19)
