This project implements the Builder pattern in Java to assemble a Gaming PC. Instead of using a huge constructor with many parameters, the Builder helps configure required and optional PC parts step by step.
- GamingPC: Product class. Holds PC specifications (CPU, GPU, RAM, Storage, Cooling, RGB).
- GamingPC.Builder: Static inner class to build the PC step-by-step.
- PCDirector: Contains presets (
buildGamingPC,buildBudgetPC). - Main: Client class to test the builds and print results.
Variables and methods clearly state what they do without needing comments.
- Example:
setCpu(),buildGamingPC(),budgetPC.
Each method in the builder just sets one field and returns this.
public Builder setCpu(String cpu) {
this.cpu = cpu;
return this;
}The build() method checks essential components before creating the object:
public GamingPC build() {
if (cpu == null || gpu == null) {
throw new IllegalStateException("CPU and GPU cannot be null");
}
return new GamingPC(this);
}The GamingPC constructor is private (can only be made via Builder), and all fields are final so they cannot be changed after creation.
private final String cpu;
private GamingPC(Builder builder) { ... }Returning this in setters lets us chain calls cleanly instead of passing many null values into a constructor:
GamingPC customPC = new GamingPC.Builder()
.setCpu("Intel Core i7-14700K")
.setGpu("NVIDIA RTX 4070 Ti")
.setRamGb(32)
.build();