Sunday, September 29, 2019

Builder Design Pattern In Java

Greetings!

Builder design pattern is a creational design pattern which helps us creating objects.

According to GoF, Builder design pattern;
"Separate the construction of a complex object from its representation so that the same construction processes can create different representations."

Eventhough the original pattern description talked about complex object creation, most used scenario is to help constructing objects fluently.
Builder design pattern helps us to assemble objects part by parts hiding inner states.

In this post i'm going to talk only about normal object creation using this pattern.



As I said earlier, this is a convienient way to construct objects with many parameters. Let's say you have a class which needs 10 parameters. Are you going to create a constructor with 10 arguments? Which is very difficult to maintain and use. This is where i'm giong to use Builder design pattern.
Help to create objects with multiple parametes in simple way.
  • Create immutable objects.
  • Encapsulates code for construction and representation.

Disadvatanges

Just like any other design, this also has few disadvantages.

  • Requires to create a separate Builder class with same number of variables.
  • For separate objects, it will need to maintain separate builders as well.

Main Class

This is the real object we need to construct. We are not exposing a constructor for this. Even we do not give any setter method.

Builder

Holds the properties of the main class. Most of the time, we use this as an inner class. We provide setter methods for all the parameters (with fancy name) and return Builder it self for furthur processing. Once the client call the build method, it creates the object of the main class.

Working Example

Let's assume that we are going to create game and we need to initialize our player object. Player may have many properties which is too big for a constructor. (though i'm not going to use many for this demo.)


package com.slmanju.patterns;

public class Player {

    private final String alias;
    private final String weapon;
    private final String hair;

    private Player(Builder builder) {
        this.alias = builder.alias;
        this.weapon = builder.weapon;
        this.hair = builder.hair;
    }

    public String getAlias() {
        return alias;
    }

    public String getWeapon() {
        return weapon;
    }

    public String getHair() {
        return hair;
    }

    @Override
    public String toString() {
        return "Player{" +
                "alias='" + alias + '\'' +
                ", weapon='" + weapon + '\'' +
                ", hair='" + hair + '\'' +
                '}';
    }

    public static class Builder {

        private final String alias;
        private String weapon;
        private String hair;

        public Builder(String alias) {
            this.alias = alias;
        }

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

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

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

}


package com.slmanju.patterns;

public class App {

    public static void main(String[] args) {
        Player player = new Player.Builder("Nero").withWeapon("Sniper").withHair("curly").build();

        System.out.println(player);
    }

}


This is not the end of the Builder design pattern. Where, I didn't cover complex scenarios like inheritance which needs a separate blog post. Though, I hope this will help you in your daily development tasks.

Happy coding :)


No comments:

Post a Comment