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

Friday, 26 May 2017

Mediator pattern

Mediator pattern defines an object that encapsulates how a set of objects interact.

Participants
Mediator - defines the interface for communication between Colleague objects.

ConcreteMediator - implements the Mediator interface.
Implements the communication and transfer the messages between the colleague objects.

ConcreteColleague - communicates with other Colleagues through its.

Before Mediator Design Pattern

 After Mediator Design Pattern


                                                            

Chat application

package designpattern.mediator;

public interface IChatMediator {
    public void sendMessage(IUser from, IUser to, String msg);

    void addUser(IUser user);
}

import java.util.ArrayList;
import java.util.List;
public class ChatMediator implements IChatMediator {
      private List<IUser> users;

      public ChatMediator() {
            this.users=new ArrayList<>();
      }

      @Override
      public void addUser(IUser user) {
            this.users.add(user);
      }

      @Override
      public void sendMessage(IUser from, IUser to, String msg) {
            to.receive(from,msg);
      }
}

public abstract class IUser {
      protected IChatMediator mediator;
      protected String name;

      public IUser(IChatMediator med, String name){
            this.mediator=med;
            this.name=name;
      }

      public abstract void send(IUser to, String msg);

      public abstract void receive(IUser from,String msg);
}

public class User extends IUser {
      public User(ChatMediator med, String name) {
            super(med, name);
      }

      @Override
      public void send(IUser to, String msg) {
            System.out.println(this.name+": Sending Message="+msg);
            mediator.sendMessage(this, to,msg);
      }
     
      @Override
      public void receive(IUser from, String msg) {
            System.out.println("Delivered from "+from.name+" to "+this.name);
      }
}

public class ChatClient {
      public static void main(String[] args) {
            ChatMediator mediator = new ChatMediator();
            IUser john = new User(mediator, "john");
            IUser micheal = new User(mediator, "micheal");
           
            mediator.addUser(john);
            mediator.addUser(micheal);
           
            john.send(micheal, "hello micheal!");
           
            micheal.send(john, "hello john!");
      }
}

Output:
john: Sending Message=hello micheal!
Delivered from john to micheal
micheal: Sending Message=hello john!
Delivered from micheal to john

Mediator Pattern usage in JDK

Java Message Service (JMS) uses Mediator pattern along with Observer pattern to allow applications to subscribe and publish data to other applications.

java.util.Timer class schedule (i.e scheduleAtFixedRate) methods.

Java Concurrency Executor execute() method.

java.lang.reflect.Method invoke() method.

Wednesday, 10 May 2017

Prototype Design Pattern

This pattern is used when creation of object directly is costly. Prototype Pattern says that cloning of an existing object instead of creating new one and can also be customized as per the requirement.

For example,
Suppose we are doing a sales analysis on a set of data from a database. Normally, we would copy the information from the database, encapsulate it into an object and do the analysis. But if another analysis is needed on the same set of data, reading the database again and creating a new object is not the best idea. If we are using the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis.





public interface Prototype {
      public abstract Object clone ( );
}

public class ConcretePrototype implements Prototype {
      public Object clone() {
            return super.clone();
      }
}

public class Client {
      public static void main( String arg[] ) {
            ConcretePrototype obj1= new ConcretePrototype ();
            ConcretePrototype obj2 = (ConcretePrototype)obj1.clone();
      }
}

Application:
Session replication from one server to another server.
Generating the GUI having many numbers of similar controls.

Advantage of Prototype Pattern
It reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of object it will be.
It lets you add or remove objects at runtime.

Usage of Prototype Pattern
When the classes are instantiated at runtime.
When the cost of creating an object is expensive or complicated.
When you want to keep the number of classes in an application minimum.
When the client application needs to be unaware of object creation and representation.

Monday, 8 May 2017

Builder Design Pattern in Java

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Instead of using numerous constructors, the builder pattern uses another object, a builder that receives each initialization parameter step by step and then returns the resulting constructed object at once.

One solution for multiple problems:

1. The intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern.
The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors.

2. Too Many arguments to pass from client program to the Factory class that can be error prone because most of the time, the type of arguments are same and from client side it’s hard to maintain the order of the argument.

3. Some of the parameters might be optional but in Factory pattern, we are forced to send all the parameters and optional parameters need to send as NULL or we need to make another constructor.

4. If the object is heavy and its creation is complex, then all that complexity will be part of Factory classes that is confusing.

How to Implement Builder Pattern?

1. We need to create a static nested class and then copy all the arguments from the outer class to the Builder class. It will be better to follow naming convention as StringBuilder class.

2. The Builder class should have a public constructor with all the mandatory attributes as parameters.

3. Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute.

4. Finally, there should be a method in the builder class that will return the Object needed by client program. For this we need to have a private constructor in the Class with Builder class as argument.
Builder Design Pattern
Example of Builder Pattern:

class Student {

      /** Mandatory fields. */
      private final String firstName;
      private final String lastName;

      /** optional fields. */
      private final int age;
      private final String phone;

      /**
       * private student constructor to assign the inner class values.
       * @param builder
       */
      private Student(StudentBuilder builder) {
            this.firstName = builder.firstName;
            this.lastName = builder.lastName;
            this.age = builder.age;
            this.phone = builder.phone;
      }

      //Only setters to provide immutability.

      public String getFirstName() {
            return firstName;
      }
      public String getLastName() {
            return lastName;
      }
      public int getAge() {
            return age;
      }
      public String getPhone() {
            return phone;
      }

      @Override
      public String toString() {
            return "Student:: "+this.firstName+": "+this.lastName+": "
                     +this.age+": "+this.phone;
      }

      public static class StudentBuilder {

            private final String firstName;
            private final String lastName;

            private int age;
            private String phone;

            /**
             * Mandatory parameters are passed through constructor.
             * @param firstName
             * @param lastName
             */
            public StudentBuilder(String firstName, String lastName) {
                  this.firstName = firstName;
                  this.lastName = lastName;
            }

            public StudentBuilder age(int age) {
                  this.age = age;
                  return this;
            }

            public StudentBuilder phone(String phone) {
                  this.phone = phone;
                  return this;
            }

            /**
             * Return the finally constructed student object.
             * @return Student object
             */
            public Student build() {
                  Student user =  new Student(this);
                  return user;
            }
      }
}

public class TestStudent {
      public static void main(String[] args) {
            // With all parameters.
            Student std1 = new Student.StudentBuilder("Rajesh", "dixit")
                                    .age(24).phone("9654900572").build();
            System.out.println(std1);

           
            // With few optional parameters.
            Student std2 = new Student.StudentBuilder("Deeshraj", "Thakur")
                                    .age(22).build();
            System.out.println(std2);

            // No optional parameters.
            Student std3= new Student.StudentBuilder("Deeshraj", "Thakur")
                                   . build();
            System.out.println(std3);
      }
}

Output:
      Student:: Rajesh: dixit: 24: 9654900572
      Student:: Deeshraj: Thakur: 22: null
      Student:: Deeshraj: Thakur: 0: null


Builder Design Pattern Example in JDK
java.lang.StringBuilder#append() (unsynchronized)
java.lang.StringBuffer#append() (synchronized)
Related Posts Plugin for WordPress, Blogger...