Search This Blog

Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Saturday, 18 March 2017

Prototype Design Pattern in Java

Prototype Design Pattern in Java

Intent
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Motivation
When we talk about object creation there is a better way to have new objects. If the cost of creating a new object is large and creation is resource intensive, we clone the object. Prototyping allows an object to create customized objects without knowing their class or any details of how to create them. This pattern involves implementing a prototype interface which tells to create a clone of the current object. 
The best example to understand Prototype Patter is, the mitotic division of a cell — resulting in two identical cells —that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.

Applicability
Use the Prototype pattern when a system should be independent of how its products are created, composed, and represented; and
·         When the classes to instantiate are specified at run-time.
·         To avoid building a class hierarchy of factories that parallels the class hierarchy of products.
·         When instances of a class can have one of only a few different combinations of state.

Consequences
The Prototype pattern has several benefits:
·         Adding and removing products at run-time.
·         Specifying new objects by varying values.
·         Specifying new objects by varying structure.
·         Reduced subclassing.
·         Configuring an application with classes dynamically.



Implementation
import java.util.ArrayList;
import java.util.List;

public class Employees implements Cloneable{

      private List<String> empList;
     
      public Employees(){
            empList = new ArrayList<String>();
      }
     
      public Employees(List<String> list){
            this.empList=list;
      }
      public void loadData(){
//This part can be used to read data from the Database and add to List
            empList.add("Ravi");
            empList.add("Ajay");
            empList.add("Sumit");
            empList.add("Pooja");
      }
     
      public List<String> getEmpList() {
            return empList;
      }

      @Override
      public Object clone() throws CloneNotSupportedException{
                  List<String> temp = new ArrayList<String>();
                  for(String s : this.getEmpList()){
                        temp.add(s);
                  }
                  return new Employees(temp);
      }
     
}

import java.util.List;

public class TestPrototypePattern {

      public static void main(String[] args) throws CloneNotSupportedException {
            Employees emps = new Employees();
            emps.loadData();
           
            //Use the clone method to get the Employee object
            Employees empsNew = (Employees) emps.clone();
            Employees empsNew1 = (Employees) emps.clone();
            List<String> list = empsNew.getEmpList();
            list.add("Simran");
            List<String> list1 = empsNew1.getEmpList();
            list1.remove("Sumit");
           
      System.out.println("Existing Employee List: "+emps.getEmpList());
System.out.println("Employee List after adding an Employee : "+list);
System.out.println("Employee List after removing an Employee : "+list1);
      }
}

Output :
Existing Employee List: [Ravi, Ajay, Sumit, Pooja]
Employee List after adding an Employee : [Ravi, Ajay, Sumit, Pooja, Simran]
Employee List after removing an Employee : [Ravi, Ajay, Pooja]

Wednesday, 22 February 2017

Builder Design Pattern in Java

Builder Design Pattern in Java
Intent
Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Motivation
As an application grows complex, the complexity of the classes and objects used also increases. Complex objects are constructed by using other objects and needs special handling when being constructed.
An application might need a mechanism for building complex objects that is independent from the ones that make up the object. In this scenario, one might want to try using the Builder design pattern.
Builder pattern allows a client object to construct a complex object by specifying only its type and content, being shielded from the details related to the objects representation. This way the construction process can be used to create different representations. The logic of this process is isolated form the actual steps used in creating the complex object, so the process can be used again to create a different object form the same set of simple objects as the first one.

Applicability
Use the Builder pattern when
·         The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.
·         The construction process must allow different representations for the object that's constructed.

Consequences
·         Builder pattern lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product. It also hides how the product gets assembled.
·         Builder pattern isolates code for construction and representation. The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented.
·         Builder pattern gives you finer control over the construction process.

Implementation
We will implement Builder Pattern by using following classes.
1.      Our first class would be Meal class, which represents food items in a meal. It represents a drink, main course, and side.
public class Meal {

      private String drink;
      private String mainCourse;
      private String side;

      public String getDrink() {
            return drink;
      }

      public void setDrink(String drink) {
            this.drink = drink;
      }

      public String getMainCourse() {
            return mainCourse;
      }

      public void setMainCourse(String mainCourse) {
            this.mainCourse = mainCourse;
      }

      public String getSide() {
            return side;
      }

      public void setSide(String side) {
            this.side = side;
      }

      public String toString() {
            return "Drink : " + drink + ", Main Course : " + mainCourse + ", Side Dish : " + side;
      }

}

2.      Here we create a Builder interface, MealBuilder. It methods will be used to build a meal and to retrieve the meal.
public interface MealBuilder {
   public void buildDrink();

   public void buildMainCourse();

   public void buildSide();

   public Meal getMeal();
}

3.      Our first implementation of MealBuilder is ItalianMealBuilder. Its constructor creates a meal. Its methods are implemented to build the various parts of the meal. It returns the meal using getMeal() method.
public class ItalianMealBuilder implements MealBuilder {

   private Meal meal;

   public ItalianMealBuilder() {
         meal = new Meal();
   }

   @Override
   public void buildDrink() {
         meal.setDrink("Martini");
   }

   @Override
   public void buildMainCourse() {
         meal.setMainCourse("Simple Spinach Lasagna");
   }

   @Override
   public void buildSide() {
         meal.setSide("Spring Green Risotto");
   }

   @Override
   public Meal getMeal() {
         return meal;
   }
}

4.      Similarly second implementation of MealBuilder is JapaneseMealBuilder. Its constructor creates a meal. Its methods are implemented to build the various parts of the meal. It returns the meal using getMeal() method.
public class JapaneseMealBuilder implements MealBuilder{
   private Meal meal;

   public JapaneseMealBuilder() {
         meal = new Meal();
   }

   @Override
   public void buildDrink() {
         meal.setDrink("Chuhai");
   }

   @Override
   public void buildMainCourse() {
         meal.setMainCourse("Tofu and Sweet Potato");
   }

   @Override
   public void buildSide() {
         meal.setSide("Onigiri");
   }

   @Override
   public Meal getMeal() {
         return meal;
   }
}





5.      The MealDirector class takes a MealBuilder as a parameter in its constructor. A different type of meal will be assembled by the MealDirector depending on the Concrete Builder passed in to the constructor.
public class MealDirector {
   private MealBuilder mealBuilder = null;

   public MealDirector(MealBuilder mealBuilder) {
         this.mealBuilder = mealBuilder;
   }

   public void constructMeal() {
         mealBuilder.buildDrink();
         mealBuilder.buildMainCourse();
         mealBuilder.buildSide();
   }

   public Meal getMeal() {
         return mealBuilder.getMeal();
   }
}

6.      The Main class is used as entry point to the application and demonstrate our builder pattern code.
public class Main {
   public static void main(String[] args) {

         MealBuilder mealBuilder = new ItalianMealBuilder();
         MealDirector mealDirector = new MealDirector(mealBuilder);
         mealDirector.constructMeal();
         Meal meal = mealDirector.getMeal();
         System.out.println("Italian Meal : " + meal);
        
         mealBuilder = new JapaneseMealBuilder();
         mealDirector = new MealDirector(mealBuilder);
         mealDirector.constructMeal();
         meal = mealDirector.getMeal();
         System.out.println("Japanese Meal : " + meal);
   }
}


When we execute the Main class we get the following output

Builder Design Pattern in Java
Builder Design Pattern in Java