Design Pattern - Builder

 Builder 

Definition 

A builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation. 

Advantages 

  • Allows you to vary a product's internal representation 
  • Encapsulates code for construction and representation 
  • Provides control over steps of construction process 

Disadvantages 

  • A distinct concrete builder must be created for each type of product
  • May hamper dependency injection. 

Builder with code 


public class Car {

private final Long id;
private final String name;

protected static class Builder {
private Long id;
private String name;

public Builder id(Long id) {
this.id = id;
return this;
}

public Builder name(String name) {
this.name = name;
return this;
}

public Car build() {
return new Car(this);
}
}

private Car(Builder builder) {
id = builder.id;
name = builder.name;
}

public static Builder builder() {
return new Builder();
}

public void runCar() {
System.out.println("Car is running");
}

}


Now we can use the static Builder class inside the Car class. Let's make a car instance using Builder class and use the method runCar() to check if it is working. 


public class BuilderMain {

public static void main(String[] args) {

Car car = Car.builder()
.id(1L)
.name("Mustang")
.build();

car.runCar();
}
}


And it seem's to work!! 



REFERENCE

https://en.wikipedia.org/wiki/Builder_pattern

Comments

Popular posts from this blog

Structures of JAVA

What is URI(URN, URL)

Spring Boot JPA - Pagination

Java Data Structures VS Python, C/C++ Data Structures

Spring Boot JPA - What is JPA, Entity, Repository

Design Pattern - Proxy