...
Code Block |
---|
|
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";
}
} |
Code Block |
---|
|
package BuilderPatternDemo;
// Builder
interface CarBuilder {
void setEngine(String engine);
void setWheels(String wheels);
void setColor(String color);
Car getResult();
} |
Code Block |
---|
|
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;
}
} |
Code Block |
---|
|
package BuilderPatternDemo;
// Director
class CarDirector {
private CarBuilder builder;
CarDirector(CarBuilder builder) {
this.builder = builder;
}
void build() {
builder.setEngine("V8");
builder.setWheels("18 inch");
builder.setColor("Red");
}
} |
Code Block |
---|
|
package BuilderPatternDemo;
public class BuilderDriver {
public static void main(String[] args) {
CarBuilder builder = new CarBuilderImpl();
CarDirector director = new CarDirector(builder);
director.build();
Car car = builder.getResult();
System.out.println(car.toString());
}
}
|
...
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.