Builder – A Creational Design Pattern

Creational Design Pattern – Initial Concept

This springcavaj – Creational Design Pattern page briefly describes the Initial Concept of Creational Design Patterns, advantages, disadvantages, benefits, various types, common problems, and a few interview questions discussed.

This guide will provide a deep understanding of Creational Design Patterns for designing and architecting an application.

What is a Builder Design Pattern?

The Builder Pattern is a Creational Design Pattern used to construct complex objects step by step. It allows for more control over the construction process, making it possible to create different types and representations of an object using the same construction code.

What are the features of the Builder Design Pattern?

  • Step-by-Step Construction – Objects are constructed through a series of steps, each responsible for building part of the object.
  • Immutable Result – Typically results in immutable objects, where the object is fully constructed before being used.
  • Reusability – The same building process can be reused to create different representations of the product.

What are the advantages of Builder Design Patterns?

  • Separation of Construction and Representation – The pattern separates the process of building a complex object from its representation, making the construction process reusable for different representations.
  • Flexibility – Allows varying the internal representation of the product, making it flexible in terms of object creation.
  • Improves Readability – With a well-structured builder, the code becomes more readable and maintainable, especially when the object has many attributes.

What are the disadvantages of Builder Design Patterns?

  • Increased Code Complexity – The Builder Pattern introduces additional classes, which can increase code complexity.
  • Not Always Necessary – For simple objects, using the Builder Pattern can be overkill and may unnecessarily complicate the codebase.

What are the use cases of Builder Design Patterns?

  • Complex Object Creation – Ideal for creating objects with many optional attributes or configuration settings.
  • Immutable Objects – Suitable for constructing immutable objects where all the required attributes are set at the time of object creation.
  • Fluent Interface – When a fluent interface (chaining method calls) is desired for constructing objects.

Brief description of implementation

I have developed a small program to help you understand the Builder Design Pattern’s Working Principle. The code is uploaded to GitHub as springcavaj-designpattern repository. Please clone the application and import in any of the IDs like either STS or Eclipse.

After successfully importing the above code base, one will find a class named BuilderMasterclassApplication.java in the package as com.springcavaj.designpattern.builder. Please see the screenshot attached below.

Here you can see the class under the com.springcavaj.designpattern.builder package is BuilderMasterclassApplication.java. Just right-click on the class, select the Run As option, and then Java Application. It will run and generate the output as provided below.

INFO com.springcavaj.designpattern.builder.BuilderMasterclassApplication - Spring Boot Object : SpringBoot [annotationController=@Controller, annotationService=@Service, annotationRepository=@Repository, annotationEntity=@Entity, isDIEnabled=true, isIOCEnabled=true]

Detailed Explanation

In this small program, I used the concept of SpringBoot concept. I have created a SpringBoot.java model, which consists of the properties annotationController, annotationService, annotationRepository, annotationEntity, isDIEnabled, isIOCEnabled. This class also contains a private Constructor which takes the reference of the SpringBootBuilder as a parameter in the constructor. As the constructor of the class is private, it is forced to use the SpringBootBuilder class to create the object of SpringBoot.

public class SpringBoot {
	
	private String annotationController;
	private String annotationService;
	private String annotationRepository;
	private String annotationEntity;
	private Boolean isDIEnabled;
	private Boolean isIOCEnabled;
	
	
	private SpringBoot(SpringBootBuilder springBootBuilder) {
		super();
		this.annotationController = springBootBuilder.annotationController;
		this.annotationService = springBootBuilder.annotationService;
		this.annotationRepository = springBootBuilder.annotationRepository;
		this.annotationEntity = springBootBuilder.annotationEntity;
		this.isDIEnabled = springBootBuilder.isDIEnabled;
		this.isIOCEnabled = springBootBuilder.isIOCEnabled;
	}
	
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("SpringBoot [annotationController=");
		builder.append(annotationController);
		builder.append(", annotationService=");
		builder.append(annotationService);
		builder.append(", annotationRepository=");
		builder.append(annotationRepository);
		builder.append(", annotationEntity=");
		builder.append(annotationEntity);
		builder.append(", isDIEnabled=");
		builder.append(isDIEnabled);
		builder.append(", isIOCEnabled=");
		builder.append(isIOCEnabled);
		builder.append("]");
		return builder.toString();
	}

	public static class SpringBootBuilder {
		
		private String annotationController;
		private String annotationService;
		private String annotationRepository;
		private String annotationEntity;
		private Boolean isDIEnabled;
		private Boolean isIOCEnabled;
		
		public SpringBootBuilder(String annotationController, String annotationRepository, String annotationEntity) {
			super();
			this.annotationController = annotationController;
			this.annotationRepository = annotationRepository;
			this.annotationEntity = annotationEntity;
		}
		
		public SpringBootBuilder setAnnotationService(String annotationService) {
			this.annotationService = annotationService;
			return this;
		}
		
		public SpringBootBuilder setDIEnabled(Boolean isDIEnabled) {
			this.isDIEnabled = isDIEnabled;
			return this;
		}
		
		public SpringBootBuilder setIOCEnabled(Boolean isIOCEnabled) {
			this.isIOCEnabled = isIOCEnabled;
			return this;
		}
		
		public SpringBoot build() {
			return new SpringBoot(this);
		}
		
	}
}

Within the same class, I have created an inner class named SpringBootBuilder which consists of all the above properties. It consists of a public Constructor where I have channeled that which all fields are mandatory to create a SpringBoot object. And, the remaining properties are not mandatory but have a setter function that returns the SpringBootBuilder object. Lastly, this inner class has a most important function named build() that returns the SpringBoot object.

public class BuilderMasterclassApplication {
	
	private static Logger logger = LoggerFactory.getLogger(BuilderMasterclassApplication.class);

	public static void main(String[] args) {
		SpringBoot springBoot = new SpringBoot.SpringBootBuilder("@Controller", "@Repository", "@Entity")
				.setAnnotationService("@Service")
				.setDIEnabled(true)
				.setIOCEnabled(true)
				.build();
		logger.info("Spring Boot Object : {}", springBoot);
	}

}

Steps to run the application

The complete Run application steps are provided in this README.md file, but still, I am providing the steps to run points below.

  • Clone the sprincavaj-designpattern application from the GitHub repository.
  • Import the application as a Maven application, either in STS or Eclipse.
  • Find the BuilderMasterclassApplication.java class.
  • Right-click on the file and select Run As -> Java Application.

GitHub Code Link

Download the Source Code from GitHub

Common Problems Faced Implementing Builder Pattern

Builder Design Pattern Common Problems

Interview FAQs

Builder Design Pattern Interview FAQs

Other Useful Links

Implementations of various components of Spring Boot

Other Design Pattern Links

Factory Design Pattern

Abstract Factory Design Pattern

Prototype Design Pattern

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *