Category Archives: Design Patterns

Design Patterns – Builder Pattern – Part V

Continuing the series of posts about design patterns, we will talk about builder pattern in this post. Builder pattern is of type creational design pattern. One of the major uses of Builder pattern is when there are too many constructor parameters to handle.

When to use Builder Pattern?

Builder pattern enforces a step by step approach to create a complex object. The object can not be used till it’s a finished product. It helps to encapsulate complex creation logic. One of the examples from real time is file creation with a format. If you are create a file about certain format (example xml, csv), you can builder pattern to create simple logical approach to creating file.

How to use Builder Pattern?

Lately working on a project to build an EDI file to transfer between customer, I have to create a file of format 834. So 834 file format varies according to different health insurance carrier. This file format contains headers, records and trailers. Headers indicate different paradigm about the file and the customer and who is sending it. To show example of builder pattern, I will use one of the headers of this file format and how it can be created using builder pattern.

One of the headers is called Transactional Group Header. This header looks like below in a real file


First field “ST” indicates that it is a transactional group. All the records for one customer can lie between ST and SE. 834 is a transaction code for file format. Since this is 834 file format, code is 834. 5432853 is a unique transaction control number, this can be anything between 4 digits in length to maximum 9 digits in length. 005010X220A1 is a implementation reference number.

Our implementation of the class with have fields for each of these field from header, a private constructor and a static builder class. This is shown below:

public class TransactionalHeader implements Serializable {
private static final long serialVersionUID = 7517644545656169045L;

private String st;

private String transactioncode;

private String transactioncontrolnumber;

private String implementationreference;

public static class Builder {

private String st;

private String transactioncode;

private String transactioncontrolnumber;

private String implementationreference;

public Builder st(String st) { = st; return this;


public Builder transactioncode(String transactioncode) {

this.transactioncode = transactioncode; return this;


public Builder transactioncontrolnumber(String transactioncontrolnumber) {                            this.transactioncontrolnumber = transactioncontrolnumber; return this;


public Builder implementationreference(String implementationreference) {                                this.implementationreference = implementationreference; return this;


public TransactionalHeader build() {

return new TransactionalHeader(this);



private TransactionalHeader(Builder builder) { =;

this.transactioncode = builder.transactioncode;

this.transactioncontrolnumber = builder.transactioncontrolnumber;

this.implementationreference = builder.implementationreference;


public String toString() {

String result = "";

StringBuffer sb = new StringBuffer();









result = sb.toString();

return result;



This was our builder class. Let’s create a demo class that will use this builder class to build an object that will give us transactional header in file. This will look like below:

public String getTransactionalHeader() {

String result = "";

TransactionalHeader th = new TransactionalHeader.Builder()





result = th.toString();

return result;


In this way, builder design pattern can be used to construct complex objects. One of the easy way to identify when to use this design pattern is when you have more than 4 or more parameters in your constructor.

Code for this post is available to download here.



Design Pattern – Abstract Factory Pattern – Part IV

In the continuation of design pattern series, till now we have covered IntroductionSingleton Pattern and Factory Pattern. In current post, we will cover the next creational type of design pattern and that is Abstract Design Pattern.

So what is abstract factory pattern?

Well, it’s an interface to create families of related or dependent objects without client knowing the implementation details.

Difference between abstract factory pattern and factory pattern

One common theme between these two patterns is that they decouple the client system from implementation details.

  • Factory pattern creates object through inheritance.
  • Abstract factory pattern creates object through composition.
  • Abstract factory provides an interface to create family of related objects.
  • Factory pattern aka factory method pattern is inherited in subclasses to create concrete objects.

In previous post, we saw an interface vehicle, implemented by different classes Car, Bus, Motorcycle, Truck and a class VehicleFactory returned different classes.

Abstract Factory pattern gives a layer of abstraction over regular factory pattern and in the process it isolates factories. The pattern returns factories of related objects. So If I want a car of Toyoto types, it can return me factories of Camry, Corolla, Avalanche etc.

Now to show Abstract Factory pattern, we will create an abstract class which will return car mileage. This will look like below:

public abstract class CarMileage {

protected double distance;
protected double gas;

public abstract void getCarMileage(double dist, double gasfilled);

public void calculateCarMileage(double dist, double gasfilled) {
double carmileage = dist / gasfilled;
System.out.println(" Your car mileage is " + carmileage);

Now each related concrete class will extend this class to return us car mileage. We will have Camry, Corolla and Avalanche as different car of types Toyota. As part of abstract factory pattern, we will add an abstract class that will return me factories of car mileage. This is shown as below:

public abstract class AbstractFactory {
public abstract CarMileage getCarMileage(String car);

A concrete subclass CarFactory of AbstractFactory, will return us different car mileage based on the car name we have passed.

public class CarFactory extends AbstractFactory {

public CarMileage getCarMileage(String car) {

if (car == null || car.equals("")) {
return null;
if (car.equalsIgnoreCase("camry")) {
return new CamryCarMileage();
} else if (car.equalsIgnoreCase("corolla")) {
return new CorollaCarMileage();
} else if (car.equalsIgnoreCase("avalanche")) {
return new AvalanceCarMileage();
return null;


To demo this by implementing a client class which will ask user input for carname, distance covered and gas filled. Based on carname, AbstractFactory will return us a factory for CarMileage. This factory of CarMileage will return us calculated car mileage for that car.

public class AbstractFactoryPatternDemo {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(;

System.out.println(" Enter the car name you want mileage for: ");

String carname = br.readLine();
System.out.println("Enter the distance covered: ");

String distanceStr = br.readLine();
double distance = Double.parseDouble(distanceStr);
System.out.println("Enter the gas you had filled: ");
String gasStr = br.readLine();
double gas = Double.parseDouble(gasStr);

AbstractFactory af = FactoryCreator.getFactory();
CarMileage cm = af.getCarMileage(carname);

cm.getCarMileage(distance, gas);




In this post, we showed how to use abstract factory pattern when we want to create a family of related objects but without specifying their concrete sub-classes.


The code for this post is available github repo.

Design Patterns – Factory Pattern – Part III

In this article, we will see how to use a factory pattern. Factory pattern is a creational type of design pattern, in short it provides a way to create objects. Another important point to note about this design pattern is that client who uses factory pattern is not aware of the implementation of factory pattern.

Even in our previous post Spring Boot REST CRUD API, we have used factory pattern to implement managers at service level. As part of this post, we will show another example of factory pattern. Factory pattern mainly used in cases when client just needs a class/object that can handle the job of doing the work at runtime without knowing any details of how it was implemented.

To show how to implement factory pattern, let’s assume we have different types of vehicles and we want to know what their maximum speed is.

Create an interface –

Our interface of vehicle will have a method to return a max speed of vehicle.

package com.betterjavacode.designpatterns.factoryexample;

public interface Vehicle {

void speed();


Now, we will have different classes (car, truck,bus,motorcycle) that will implement this interface to return their maximum speed. For article purposes, we will only be showing one class.

package com.betterjavacode.designpatterns.factoryexample;

public class Car implements Vehicle {

 public void speed() 

   System.out.println("Max Speed of this car is 100 mph");


To get an instance of an object, we will create a factory class that will return me appropriate instance of vehicle object based on what vehicle type I pass.

package com.betterjavacode.designpatterns.factoryexample;

public class VehicleFactory {

public Vehicle getVehicle(String vehicleType)
   if (vehicleType == null) 
      return null;
   if (vehicleType.equalsIgnoreCase("car")) {
     return new Car();
   if (vehicleType.equalsIgnoreCase("bus")) {
     return new Bus();
   if (vehicleType.equalsIgnoreCase("motorcycle")) 
     return new Motorcycle();
   if ( vehicleType.equalsIgnoreCase("truck")) 
     return new Truck();
    return null;


A factory pattern demo class will get any of object of type vehicle at runtime.

package com.betterjavacode.designpatterns;

import com.betterjavacode.designpatterns.factoryexample.Vehicle;
import com.betterjavacode.designpatterns.factoryexample.VehicleFactory;

public class FactoryPatternDemo {

public static void getSpeed(String vehicleType) {
 VehicleFactory vehicleFactory = new VehicleFactory();

Vehicle veh1 = vehicleFactory.getVehicle(vehicleType);



In this example, we have shown how to implement a design pattern type factory pattern. The code for this is available design patterns.


  1. Factory Pattern Example
  2. Factory Pattern

Design Patterns – Singleton Pattern – Part II

In this post, we will discuss Singleton Pattern which is of Creational type design pattern. You can checkout the introductory post about design patterns here.

Singleton Design Pattern

Singleton design pattern is the simplest design patterns in software engineering. As Singleton is a creational type of design pattern, it is used to create an object.

In this design pattern, a single class creates an object , but also makes sure that only a single object is created. This class provides a way to access the object, so to avoid the need to instantiate the object.


In this design pattern a class will have a private constructor and a static method to provide access to static member of the class instance. Most of the time singleton pattern is used in logger and configuration classes implementation.

package com.betterjavacode.designpatterns;

public class SingletonDemo {

private static SingletonDemo demo;

private SingletonDemo()



public static SingletonDemo getInstance()

if (demo == null)
demo = new SingletonDemo();

return demo;

public void printSingletonDemo()

System.out.println(" This is a singleton design pattern demo ");


Now any client code who wants to use SingletonDemo class, can do this with SingletonDemo.getInstance(). Major advantage of Singleton design pattern is it allows only one instance of object is created.


Code for this post is available to download design patterns.

Design Patterns in Java – Introduction

In coming next few posts, we will build a series of posts to discuss design patterns in Java. In this introductory post, we will give a brief idea about design patterns.

What are design patterns?

Design patterns are programming strategies independent of programming language to build a solution for common object-oriented programming problems. One of the major benefits of design patterns is that the most code is reusable and easily maintainable.

Example of design pattern in real world?

To understand what exactly design patterns are, let’s consider a real life example. Suppose we have an animal class. All the subclasses for animals like Elephant, Dog, Cat can be built by using methods to make these objects.

An abstract factory is a design pattern, that can be used in this example.

abstract class AbstractAnimalFactory


public Elephant makeElephant() {

return new Elephant();


public Dog makeDog(){

return new Dog();




abstract class Animal{



class Elephant extends Animal{



class Dog extends Animal{




Types of design patterns

Based on their purpose, design patterns are divided into three types of patterns creational, structural and behavioral. Further, each of these design patterns have sub-types.

Creational Design Pattern

  1. Singleton Design Pattern
  2. Factory Pattern
  3. Absolute factory Pattern
  4. Builder Pattern
  5. Prototype Pattern

Structural Design Pattern

  1. Adapter Pattern
  2. Composite Pattern
  3. Proxy Pattern
  4. Flyweight Pattern
  5. Facade Pattern
  6. Bridge Pattern
  7. Decorator Pattern

Behavioral Design Pattern

  1. Template Method Pattern
  2. Mediator Pattern
  3. Chain of responsibility Pattern
  4. Observer Pattern
  5. Strategy Pattern
  6. Command Pattern
  7. State Pattern
  8. Visitor Pattern
  9. Interpreter Pattern
  10. Iterator Pattern
  11. Memento Pattern

In coming posts, we will discuss each design pattern with a production-ready example.

Advantages of design patterns

  1. Reusable in multiple projects
  2. Capture the complete experience of software engineering
  3. Provide clarity to system architecture


In this post, we discussed a simple introduction to design patterns. In coming posts, we will build actual design patterns to show how design patterns work.


  1. Design patterns in Java
  2. Design Patterns Brief Introduction