Showing posts with label DESIGN PATTERN - CREATIONAL. Show all posts
Showing posts with label DESIGN PATTERN - CREATIONAL. Show all posts

Thursday, March 30, 2017

Builder Design Pattern Using Java 8

INTRODUCTION

Builder design pattern is mainly focused on creating a complex object. Creation of complex object will be done by the sequence of smaller steps, i.e splitting the complex logic into multiple simple units. These simple units can be reused again. The whole complex object creation will be controlled by a controller/builder.
In this article, we are going to implementation the Builder Design Pattern using java before and after the version Java 8.

USECASE

Assembling a bike with its components like Engine, Wheel, and Gear etc.,

IMPLEMENTATION - BEFORE JAVA 8

Assembling a bike will have many activities like assembling the engine, wheel, estimating the cost and finally naming the bike etc,.
Lets us create Model Class - Bike.
public class Bike {
 private String name;
 private String wheelType;
 private String engineType;
 private int cost;
 //getters and setters
}


Create Builder interface with the list of activities.

public interface BikeBuilder {
 Void setName();
 void assembleEngine();
 void assembleWheel();
 void estimateCost();
 Bike getBike();
}

Now implement the BikeBuilder and create different bikes like HeroBike, RoyalEnfield Bike.

public class RoyalEnfield implements BikeBuilder {

 private Bike bike;

 RoyalEnfield() {
 bike = new Bike();
 }

 public void assembleWheel() {
 bike.setWheelType("Spoke");
 }

 public void estimateCost() {
 bike.setCost(170000);
 }

 public void assembleEngine() {
 bike.setEngineType("Diesel");
 }

 public void setName() {
 bike.setName("RoyalEnfield");
 }

 public Bike getBike() {
 return bike;
 }
}

Now time to test the builder pattern.

public class BuilderPatternMain {

public static void main(String[] args) {

 BikeBuilder heroBikeBuilder = new HeroBike();
 heroBikeBuilder.assembleWheel();
 heroBikeBuilder.assembleEngine();
 heroBikeBuilder.estimateCost();
 heroBikeBuilder.setName();

 // Get Hero Bike
 System.out.println(heroBikeBuilder.getBike().toString());

 BikeBuilder enfieldBike = new RoyalEnfield();
 enfieldBike.assembleWheel();
 enfieldBike.assembleEngine();
 enfieldBike.estimateCost();
 enfieldBike.setName();

 // Get Royal Enfield Bike
 System.out.println("\n" + enfieldBike.getBike().toString());
 }
}

IMPLEMENTATION - USING JAVA 8

New Java 8 Features like Lambda Expression, Streams, Method References etc., helps the developers to develop clear, easy understanding and simple code.
A separate package has been introduced for Functional Interfaces (java.util.function) as part of Java 8 release.
Here I am going to use Consumer Interface from java.util.function package ( to know more about Consumer Interface check out Functional Interface article).
No change in Bike.java  class.
  1. Return the HeroBike/RoyalEnfield object for assembleEngine(), assembleWheel(), estimateCost() and setName() methods.
  2. Modify the getBike() method, so that it will accept the Consumer object as an argument and also creates the HeroBike/RoyalEnfield object.

import java.util.function.Consumer;

public class HeroBike {

 private static Bike bike;

 public HeroBike assembleEngine() {
   bike.setEngineType("Petrol");
   return this;
 }

 public HeroBike assembleWheel() {
   bike.setWheelType("Alloy");
   return this;
 }

 public HeroBike estimateCost() {
   bike.setCost(50000);
   return this;
 }

 public HeroBike setName() {
   bike.setName("Hero");
   return this;
 }

 public Bike getBike(Consumer<HeroBike> heroBike) {
   bike = new Bike();

   HeroBike newHeroBike = new HeroBike();
   heroBike.accept(newHeroBike);

   return bike;
}
}

Check out below how easy is to implement the Builder Pattern using java 8.

public class BuilderPatternMainJava8 {

 public static void main(String[] args) {
   HeroBike heroBike = new HeroBike();
   System.out.println(heroBike.getBike(
     bike -> bike.assembleEngine()
                  .assembleWheel()
                  .estimateCost()
                  .setName())
                  .toString());

   RoyalEnfield royalEnfield = new RoyalEnfield();
   System.out.println("\n" + royalEnfield.getBike(
     bike -> bike.assembleEngine()
                 .assembleWheel()
                 .estimateCost()
                 .setName())
                 .toString());
 }
}

Here we have eliminated calling the method from the object again and again. Also, makes the code clear and easy understanding.

Hope this example clarifies the Builder Design Pattern Using Java 8. Please share your comments below.
Happy Knowledge Sharing!!!

Tuesday, July 1, 2014

Builder Design Pattern in Java

INTRODUCTION

In the real world, a product built with two or more parts which may be complex or simple in nature. The builder pattern helps to build a complex product by building it's parts (may be simple) one by one (should maintain the order).

USECASE

Assembling a bike with its components like Engine, Wheel, and Gear etc.,

IMPLEMENTATION

Lets us create Model Class - Bike.
public class Bike {

 private String wheelType;
 private String engineType;
 private int cost;
 //getters and setters
}


The process of assembling a new bike will have set of activities. So my Builder class will have the following activities.

public interface BikeBuilder {
 void assembleEngine();
 void assembleWheel();
 void estimateCost();
 Bike getBike();
}

Now implement the BikeBuilder and create different bikes like HeroBike, RoyalEnfield Bike.

public class HeroBike implements BikeBuilder {

 private Bike bike;

 HeroBike() {
   bike = new Bike();
 }

 @Override
 public void assembleWheel() {
   bike.setWheelType("Alloy");
 }

 @Override
 public void estimateCost() {
   bike.setCost(50000);
 }

 @Override
 public void assembleEngine() {
   bike.setEngineType("Petrol");
 }

 @Override
 public Bike getBike() {
   return bike;
 }
}

Actually, the assembling of a bike will be done in a factory where the activities have done one by one sequentially. So create a factory.

public class BikeFactory {
 public void assemble(BikeBuilder bikeAssembler) {
   bikeAssembler.assembleWheel();
   bikeAssembler.assembleEngine();
   bikeAssembler.estimateCost();
 }
}

Now time to test the builder pattern.

public class BuilderPatternTest {

 public static void main(String[] args) {
   BikeBuilder assembler = null;
   BikeFactory bikeFactory = new BikeFactory();

   // Hero Bike
   System.out.println("=========HERO BIKE======");
   assembler = new HeroBike();
   bikeFactory.assemble(assembler);
   Bike heroBike = assembler.getBike();
   System.out.println("Cost: " + heroBike.getCost());
   System.out.println("Engine Type: " + heroBike.getEngineType());

   // Yamaha Bike
   System.out.println("=========ROYAL ENFIELD BIKE=====");
   assembler = new RoyalEnfield();
   bikeFactory.assemble(assembler);
   Bike yamahaBike = assembler.getBike();
   System.out.println("Cost: " + yamahaBike.getCost());
   System.out.println("Engine Type: " + yamahaBike.getEngineType());
 }
}

OUTPUT

=========HERO BIKE===============
Cost: 50000
Engine Type: Petrol

=========ROYAL ENFIELD BIKE===============
Cost: 170000
Engine Type: Diesel

Complete Source Code

Hope this example clarifies the Builder Design Pattern. Please share your thoughts in the comments box.
Happy Knowledge Sharing!!!

Abstract Factory Design Pattern in Java

INTRODUCTION

We have got some idea about the Factory Method Design Pattern, but what is Abstract Factory Design Pattern? It is nothing but the FACTORY of FACTORIES. A factory which provides the another factory based on the input provided.

USECASE

Get the state’s (within India) language based on the North India and South India states.

IMPLEMENTATION

Lets create a State Interface.
public interface State {
 String getLanguage();
}

Create States Tamilnadu, Andra, Gujarath, and Delhi which implements the State Interface.
public class Tamilnadu implements State {
 @Override
 public String getLanguage() {
   return "tamil";
 }
}

Create an IndiaFactory interface which is implemented by SouthIndiaFactory and NorthIndiaFactory.
public interface IndiaFactory {
 State getState(String stateName);
}


Now create SouthIndiaFactory which has the south India's states Tamilnadu & Andra and create NorthIndiaFactory which has Delhi & Gujarat.
public class SouthIndiaFactory extends IndiaFactory {

 @Override
 State getState(String stateName) {
   if (stateName.equalsIgnoreCase("tamilnadu")) {
     return new Tamilnadu();
   } else if (stateName.equalsIgnoreCase("andra")) {
     return new Andra();
   }
   return null;
 }
}

Now time to test the Abstract Factory pattern.
public class AbstractFactoryPatternTest {

 public static void main(String[] args) {
   // South India
   IndiaFactory southIndiaFactory = IndiaFactoryProducer.getDivision("south");
   State tamilnadu = southIndiaFactory.getState("tamilnadu");
   System.out.println("Tamilnadu's language: " + tamilnadu.getLanguage());
   State andra = southIndiaFactory.getState("andra");
   System.out.println("Andra's language: " + andra.getLanguage());

   // North India
   IndiaFactory northIndiaFactory = IndiaFactoryProducer.getDivision("north");
   State gujarath = northIndiaFactory.getState("gujarath");
   System.out.println("Gujarath's language: " + gujarath.getLanguage());
   State delhi = northIndiaFactory.getState("delhi");
   System.out.println("Delhi's language: " + delhi.getLanguage());
 }
}
OUTPUT

Tamilnadu's language: tamil
Andra's language: telugu
Gujarath's language: gujarathi
Delhi's language: hindi

Complete Source Code

Hope this example clarifies the Abstract Factory Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!

Friday, June 27, 2014

Singleton Design Pattern in Java

INTRODUCTION

Singleton design pattern is one of the popular design patterns in java.
The straightforward understanding from the singleton is the single instance. Yes, only one instance of any singleton class can be created throughout the application.

WHEN TO USE

  1. When the business requirement is to create only one instance for the application.
  2. If you want to avoid creating multiple objects for a class.
  3. Need to restrict the creating an object for your class.

HOW TO IMPLEMENT

Java access specifier actually makes the class singleton. How? make the constructor as private so that it can not be extended by other class.
Consider the below example.
public class Singleton {
 // Declare an instance of this class private static
 private static Singleton _singletonInstance;

 /**
  * Make the constructor as private, so that it can't be sub-classed
  */
 private Singleton() {
 }

 /**
  * Has the logic to create a new Instance for Singleton class. static keyword
  * helps to access this method directly. synchronized - helps to avoid
  * multiple instances created by the multiple threads in case.
  *
  * @return
  */
 public static synchronized Singleton getSingletonInstance() {

   if (null == _singletonInstance) {
     _singletonInstance = new Singleton();
   }

   return _singletonInstance;
 }
}


Also, It is marked as static to make method accessible directly using the class name, synchronized makes the method thread-safe so that no other thread can access this method and try to create multiple instances.

Also, I am having simple java class to create multiple instances and test the singleton feature.

public class SampleJava {
 public String getName() {
   return "Sample Java";
 }
}

Now time to test the singleton design pattern. Try to create 2 or more instances for the SampleJava class and check how many instances are actually created.

public class SingletonTest {

 public static void main(String[] args) {

   // Create a instance for the Singleton class
   Singleton s1 = Singleton.getSingletonInstance();

   // Create another instance
   Singleton s2 = Singleton.getSingletonInstance();

   System.out.println("Are s1 and s2 same? : " + (s1 == s2));

   SampleJava sj1 = new SampleJava();
   SampleJava sj2 = new SampleJava();

   System.out.println("Are sj1 and sj2 same? : " + (sj1 == sj2));
 }
}

OUTPUT


Are s1 and s2 same? : true
Are sj1 and sj2 same? : false
Hope this example clarifies the Singleton Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!