What is the Factory Builder design pattern?
sobes.tech AI
Answer from AI
Factory Builder pattern, or rather Factory Method combined with Builder, is a combination of two patterns that improves the creation of complex objects.
Factory Method defines an interface for creating an object but allows subclasses to decide which class to instantiate. It delegates the responsibility of object creation to subclasses.
Builder separates the construction of a complex object from its representation so that the same construction process can create different representations. It allows step-by-step creation of an object using a chain of method calls.
The combination of these patterns is most often found in scenarios where it is necessary to create several variants of a complex object. Factory Method determines which type of Builder should be used, and the Builder then handles how to create an object of that type with various configurations.
Example of usage: When you have a hierarchy of object classes requiring complex initialization, and you want to create these objects with different configurations.
Typical interaction structure:
- Factory: Has a method that returns an instance of a specific Builder depending on input parameters or its type.
- Builder: Has methods for step-by-step configuration of the complex object and a final
build()method that returns the finished object. - Product: The complex object created by the Builder.
Advantages:
- Improved readability and manageability of code when creating complex objects.
- Flexibility in creating different configurations of the same object type.
- Separation of object creation logic from its representation.
- Simplification of adding new product types (using Factory Method) or new building methods (using Builder).
Disadvantages:
- Increased number of classes in the project.
- May be excessive for simple objects.
Example (pseudocode):
// Product
class ComplexObject {
private String partA;
private int partB;
// private constructor
private ComplexObject(String partA, int partB) {
this.partA = partA;
this.partB = partB;
}
// Inner Builder class
public static class Builder {
private String partA;
private int partB;
public Builder setPartA(String partA) {
this.partA = partA;
return this;
}
public Builder setPartB(int partB) {
this.partB = partB;
return this;
}
public ComplexObject build() {
return new ComplexObject(partA, partB);
}
}
}
// Factory returning Builder
class ComplexObjectFactory {
public static ComplexObject.Builder createDefaultBuilder() {
return new ComplexObject.Builder()
.setPartA("defaultA")
.setPartB(10);
}
public static ComplexObject.Builder createSpecialBuilder() {
return new ComplexObject.Builder()
.setPartA("specialA")
.setPartB(50);
}
}
// Usage:
// ComplexObject obj1 = ComplexObjectFactory.createDefaultBuilder().build();
// ComplexObject obj2 = ComplexObjectFactory.createSpecialBuilder().setPartA("customA").build();