Builder Pattern Demo
package BuilderPatternDemo;
// Product
class Car {
private String engine;
private String wheels;
private String color;
public void setEngine(String engine) {
this.engine = engine;
}
public void setWheels(String wheels) {
this.wheels = wheels;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Car:\n\tEngine: " + engine + "\n\tWheels: " + wheels + "\n\tColor: " + color + "\n";
}
}
package BuilderPatternDemo;
// Builder
interface CarBuilder {
void setEngine(String engine);
void setWheels(String wheels);
void setColor(String color);
Car getResult();
}
package BuilderPatternDemo;
// ConcreteBuilder
class CarBuilderImpl implements CarBuilder {
private Car car;
CarBuilderImpl() {
this.car = new Car();
}
public void setEngine(String engine) {
car.setEngine(engine);
}
public void setWheels(String wheels) {
car.setWheels(wheels);
}
public void setColor(String color) {
car.setColor(color);
}
public Car getResult() {
return car;
}
}
In this example, Car
is the complex object (the product) that we are trying to build. The CarBuilder
interface defines the steps that are necessary to build a car, and CarBuilderImpl
(the concrete builder) implements these steps. CarDirector
(the director) uses the CarBuilder
to create a car. This allows us to construct a Car
object step-by-step, and the construction process can be different for different types of cars.