Builder design pattern in java

  • Creational design pattern

When to use builder design pattern?

  • The 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.
  • Creating and assembling the parts of a complex object directly within a class is inflexible. It commits the class to creating a particular representation of the complex object and makes it impossible to change the representation later independently from (without having to change) the class.

The Builder design pattern solves problems like:

  • How can a class (the same construction process) create different representations of a complex object?
  • How can a class that includes creating a complex object be simplified?

Features of Builder Design Pattern

  • Used when you don’t know enough parameters about creating the object via constructor but you add parameters to an objects via setters of another class and you extract the main object out of it.
public class Phone {
	private String os;
	private int ram;
	private String processor;
	private double screenSize;
	private int battery;
	
	public Phone(String os, int ram, String processor, double screenSize, int battery) {
		super();
		this.os = os;
		this.ram = ram;
		this.processor = processor;
		this.screenSize = screenSize;
		this.battery = battery;
	}

	@Override
	public String toString() {
		return "Phone [os=" + os + ", ram=" + ram + ", processor=" + processor + ", screenSize=" + screenSize
				+ ", battery=" + battery + "]";
	}
}

public class PhoneBuilder {
	private String os;
	private int ram;
	private String processor;
	private double screenSize;
	private int battery;
	
	public PhoneBuilder setOs(String os) {
		this.os = os;
		return this;
	}
	public PhoneBuilder setRam(int ram) {
		this.ram = ram;
		return this;
	}
	public PhoneBuilder setProcessor(String processor) {
		this.processor = processor;
		return this;
	}
	public PhoneBuilder setScreenSize(double screenSize) {
		this.screenSize = screenSize;
		return this;
	}
	public PhoneBuilder setBattery(int battery) {
		this.battery = battery;
		return this;
	}
	
	public Phone getPhone() {
		return new Phone(os, battery, processor, screenSize, battery);
	}
}

public class Shop {
	public static void main(String[] args) {
		Phone p1 = new Phone("Android",1080,"QualComm",5.5,3100);
		System.out.println(p1);
		Phone p2 = new PhoneBuilder().setBattery(1000).setOs("Android").getPhone();
		System.out.println(p2);
	}
}

References Read Me :

Leave a Comment