Builder Design Pattern Example in Java

Builder design pattern is used to construct complex object step by step before building the final object. We need builder design pattern when we have lot of parameters and some of them are mandatory to create object and others are optional. Else we can maintain many constructors to achieve the same, which is very complex to maintain.

public class BuilderPattern {

	public static void main(String args[]) {

		// Create the object using builder pattern

		Cake whiteCakeNonVeg = new Cake.Builder().sugar(1).butter(0.5).eggs(2)
				.vanila(2).bakingpowder(0.75).milk(0.5).build();

		// Don't need egg
		Cake whiteCakeVeg = new Cake.Builder().sugar(1).butter(0.5).vanila(2)
				.bakingpowder(1.75).milk(0.5).flour(2).build();

		System.out.println(whiteCakeNonVeg);
		System.out.println(whiteCakeVeg);
	}
}

class Cake {
	private final double milk;
	private final double sugar;
	private final double butter;
	private final int eggs;
	private final double bakingpowder;
	private final int vanila;
	private final double flour;

	// constructor should be private to enforce object creation through builder
	private Cake(Builder builder) {
		this.milk = builder.milk;
		this.sugar = builder.sugar;
		this.butter = builder.butter;
		this.eggs = builder.eggs;
		this.bakingpowder = builder.bakingpowder;
		this.vanila = builder.vanila;
		this.flour = builder.flour;

	}

	public static class Builder {
		private double milk;
		private double sugar;
		private double butter;
		private int eggs;
		private double bakingpowder;
		private int vanila;
		private double flour;

		public Builder milk(double cup) {
			this.milk = cup;
			return this;
		}

		public Builder sugar(double cup) {
			this.sugar = cup;
			return this;
		}

		public Builder butter(double cup) {
			this.butter = cup;
			return this;
		}

		public Builder eggs(int number) {
			this.eggs = number;
			return this;
		}

		public Builder vanila(int spoon) {
			this.vanila = spoon;
			return this;
		}

		public Builder bakingpowder(double spoon) {
			this.bakingpowder = spoon;
			return this;
		}

		public Builder flour(double cup) {
			this.flour = cup;
			return this;
		}

		// return fully build object
		public Cake build() {
			return new Cake(this);
		}
	}

	@Override
	public String toString() {
		return "Cake { milk=" + milk + "sugar=" + sugar + ", butter=" + butter
				+ ", eggs=" + eggs + ", vanila=" + vanila + ", bakingpowder="
				+ bakingpowder + ", flour=" + flour + '}';

	}

}
Output
Cake { milk=0.5sugar=1.0, butter=0.5, eggs=2, vanila=2, bakingpowder=0.75, flour=0.0} Cake { milk=0.5sugar=1.0, butter=0.5, eggs=0, vanila=2, bakingpowder=1.75, flour=2.0}


















Receive Latest Java Examples in Your Email: