Mediator Pattern

Mediator Pattern:

  • In our day to day Programming life, We are dealing with  large set of projects In the samewhile frequently getting Changes in the existing project as well as adding new features in the project.In this total Life Cycle We are playing with huge set of objects.
  • In this situation If objects are sharing their references with eachother. then It will be very difficult to maintian the project.

For this Scenario Mediator Pattern Comes to play,

Instead of eachother Communication.We introduce one Mediator who is responsible for the communication between the objects.

  • Mediator holds the reference of all objects and
  • Each object holds the reference of Mediator.

Example:

                     Group Chat is the  best example for the Mediator Pattern.One Person in a group sends a message it need to deliever to all other Members in a group.

                   In this Situation,He need to send message to mediator and mediator is responsible to deliver message to all other members.


                                                      IGroupChatMediator.java

 package com.example.mediator;  
 import com.example.user.User;  
 public interface IGroupChatMediator {  
      public void sendMessage(String message,User user);  
      public void addUser(User user);  
 }  


                                                       GroupChatMediator.java
 package com.example.mediator;  
 import java.util.ArrayList;  
 import java.util.List;  
 import com.example.user.User;  
 public class GroupChatMediator implements IGroupChatMediator{  
      private List<User> users;  
      public GroupChatMediator() {  
           users=new ArrayList<User>();  
      }  
      @Override  
      public void sendMessage(String message,User user) {  
           for (User eachUser : users) {  
                if (eachUser!=user) {  
                     eachUser.recieveMessage(message);  
                }  
           }  
      }  
      @Override  
      public void addUser(User user) {  
           users.add(user);  
      }  
 }  


                                                             AbstractUser.java
 package com.example.user;  
 import com.example.mediator.IGroupChatMediator;  
 public abstract class AbstractUser {  
      protected IGroupChatMediator chatMediator;  
      protected String userName;  
      public String getUserName() {  
           return userName;  
      }  
      public AbstractUser(IGroupChatMediator groupChatMediator, String name) {  
           chatMediator=groupChatMediator;  
           userName=name;  
      }  
      public abstract void sendMessage(String message);  
      public abstract void recieveMessage(String message);  
 }  


                                                                    User.java
 package com.example.user;  
 import com.example.mediator.IGroupChatMediator;  
 public class User extends AbstractUser{  
      public User(IGroupChatMediator groupChatMediator,String name) {  
           super(groupChatMediator, name);  
      }  
      @Override  
      public void sendMessage(String message) {  
           System.out.println(getUserName()+" sending message: "+message);  
           chatMediator.sendMessage(message,this);  
      }  
      @Override  
      public void recieveMessage(String message) {  
           System.out.println(getUserName()+" recieving message :"+message);  
      }  
 }  


                                                                       Client.java
 package com.example.test;  
 import com.example.mediator.GroupChatMediator;  
 import com.example.mediator.IGroupChatMediator;  
 import com.example.user.User;  
 public class Client {  
      public static void main(String[] args) {  
           IGroupChatMediator chatMediator=new GroupChatMediator();  
           User user1=new User(chatMediator, "ganesh");  
           User user2=new User(chatMediator, "dinakar");  
           User user3=new User(chatMediator, "mahesh");  
           chatMediator.addUser(user1);  
           chatMediator.addUser(user2);  
           chatMediator.addUser(user3);  
           user1.sendMessage("hai all");  
      }  
 }  

Null Object Pattern

Null Object Pattern:

  • In NULL object Pattern, Null object replaces check of  Null object instances, 
  • Logic for dealing with a null field or variable is duplicated throughout your code.
  • Replace the null logic with a Null Object, an object  that provides the appropriate null behavior. 
  • Method should not return Null at any circumstances while invoking it,Instead It should return Null object.So that Caller Can avoid checking null logic.

Essence of Polymorphism:

  • The essence of polymorphism is that instead of asking an object what type it is and then invoking some behavior based on the answer, you just invoke the behavior.
  • The object, depending on its type, does the right thing. One of the less intuitive places to do this is where you have a null value in a field. 

Real Time Scenario:

  • If client calls any method  and it  returns some object . Before using that object we will do null check with that object,
  • But Null object Pattern says that We should avoid such null check.Instead We directly have to use that object by trusting it.

Sample Code:

       
if(customer!=null){
   name=customer.getName();
}else{
   name="unKnown"
}
             
Once We Implemented NULL Object Pattern, Then We can avoid some sort of unneccessary if condition codes.

       
   name=customer.getName();
             

LikeWise For Collections:

Instead of returning NULL,return empty collection like below.


List Set Map
Collections.emptyList() Collections.emptySet() Collections.emptyMap()

Note: The above methods always returns same immutable empty collections everytime it needs to return an empty collection.So need to worry about the multiple creation of objects.

Example:


ICustomer.java
1:  public interface ICustomer {  
2:        String getName();  
3:        Boolean isNull();  
4:  }  


Customer.java
1:  public class Customer implements ICustomer{  
2:       String name;  
3:       public Customer(String name){  
4:            this.name=name;  
5:       }  
6:       @Override  
7:       public Boolean isNull(){  
8:            return false;  
9:       }  
10:       @Override  
11:       public String getName(){  
12:            return name;  
13:       }  
14:  }  


NullCustomer.java
1:  public class NullCustomer implements ICustomer {  
2:       private static NullCustomer nullCustomer=new NullCustomer();  
3:       private NullCustomer(){  
4:       }  
5:       public NullCustomer getInstance(){  
6:            return nullCustomer;  
7:       }  
8:       @Override  
9:       public String getName() {  
10:            return "UnKnown";  
11:       }  
12:       @Override  
13:       public Boolean isNull() {  
14:            return true;  
15:       }  
16:  }  


CustomerFactory.java
1:  public class CustomerFactory {  
2:       public ICustomer getCustomer(String name){  
3:            ICustomer customer;  
4:            if(name.equalsIgnoreCase("ganesh")){  
5:                 customer=new Customer(name);  
6:            }else{  
7:                 customer=NullCustomer.getInstance();  
8:            }  
9:            return customer;  
10:       }  
11:  }  


If any Client access the getCustomer(String name) method,It either returns Customer object or NullCutomer, there is no possibility to get Null Object.

So Method invoker  can avoid if condition by checking the object is Null or not.

One more Advantage is that eventhough if he forgets it, there is no possibility of Null Pointer Exception.

But In Some Situation, We will identity the flow based on  the returned object.For that purpose I introduced isNull() function in the ICustomer,


  • For Customer object it returns false 
  • For NullCustomer object it returns true.
And also I made the NullCustomer Class as Singleton Class. Because Its state never going to change and also we were avoided multiple creation of objects.


 ICustomer customer=CustomerFactory.getCustomer("ganesh");  
 if(customer.isNull()){  
 //doAlternativeBehaviour  
 }else{  
 //doOrginal Behaviour  
 }  

Note: Still there is no removal of null check with the code  but avoided the possibility of Null Pointer Exception.


Additional Refractoring with Null Object Pattern:

Lets us consider that we already developed the  project and we are not interested to touch the existing Customer class to add any extra code,

In this Situation,Is it possible to implement the Null Object Pattern.

Yess!!!!!!!! We can do it with the help of Testing Interface Concept.

Create one marker Interface NullValue,

 public interface NullValue{  
 }  

NullObject Pattern should implement above interface too and replace the Customer.isNull() with the below code.

 ICustomer customer=CustomerFactory.getCustomer("ganesh");  
 if(customer instanceof NullValue){  
 //doAlternativeBehaviour  
 }else{  
 //doOrginal Behaviour  
 }  

Everthing done!!!!!!!!

Now We can easily differenciate the object.


Types of EJB


             Basically Ejb is divided into two types.One is Session Beans and another is Message Driven Beans(MDB), In this article We are going to see only about Session Beans.We will have a separate article on MDB.


Session Bean:

                   In the 3-tier Architecture design ,Business Layers usually contains Session Beans classes. This Session Beans class is nothing but the normal class annotated with three EJB session bean Components(Stateless,Stateful,Singleton).

Why we need to declare normal class into the Session Bean class?

 Once we declared our class as Session Bean class then it can avail all the features provided by the Ejb container.

Who are all the Clients for Session Bean?

  1. Clients who call session Bean from the Presentation Layer( html or jsp ) within the Application server. 
  2. Clients can be a  session bean who call another session bean with the Application server (i.e Same JVM) usually called as Local Client.
  3. Clients can be a session bean who call another session bean from the another Application server(i.e Different JVM) usually called as Remote Client.
Note: Each session bean must contain interfaces for their class.At the Run time EJB provides runtime implementation for all the session bean interfaces,When clients calling the session beans Ejb won't allow clients to call  Session beans classess directly instead all calls goes to the proxy classess.

What is this Proxy Classess?

                   This proxy classes maintly used to do container managed things like transaction management,security,asynchornous thread management etc...

 Session Beans are sub-divided into 3 types,


  1. Stateless
  2. Stateful
  3. Singleton

Stateless Session Beans: (Does not maintain state of a client)

                           For stateless session beans EJB container create a pool of instances for a each stateless beans.And also it does not maintain client state, what it means? lets see the diagram.

Stateless Session Bean



                                  
                                  Consider that our application contain single session bean class which deployed in the application server.

                                  At the run-time ejb container container created pool of instance for a our stateless session bean class.

Why EJB container creates pool of instances for a Stateless Session Bean? 


                  In the Enterprise application several client will call the session bean at a time.To serve fast services to the clients EJB container creates this pool of instances when application started. 

Before I told that it does not maintain the state.

            Consider that client contain the set of methods,first method make a call to the session bean in that time container randomly pick the instance and returns to the client.In the next method call client makes a call to the same session bean.In this time client wont get the instance object which returns previously Ejb container randomly pick any instance from the pool of the instance and return it back to the client.It clears that its not maintaining the client state.


Stateful Session Beans: ( Maintains client state across each request, one bean instance per client)


                                   In Stateful session bean EJB container creates single session bean instance for each client.And also note that it won't create pool of instance like stateless  at the application startup.It creates instance when the client makes request to the bean.And also it provides same bean instance for each subsequent request call from the client.


Stateful Session Bean




Singleton Session Beans: ( One bean instance per application server)

                                     Same as like in design patterns , In singleton session Bean EJB Container creates one instance for whole application.so any number of client will request for the session bean only one instance is shared accross the clients.




Singleton Session Bean



Hope It is Informative.If you are not understood fully don't worry We will have nice programmatic example for each Session Beans in upcoming Articles.


Thanks Have a Happy Learning...



































A Quick Start

EJB- Simple Introduction:

 We all know that the Enterprise Applications are developed with the set of layers like 3-tier or n-tier architecture. Based on the requirement,we develop our project with some set of  the layers. But Commonly we can find 3-tier architecture in most of the Java Enterprise Application.
                                     
                                         1.Presentation Layer
                                         2.Business Layer
                                         3.Persistance Layer

Persentation layer  is responsible for user interface in which user can interact(html and jsp)

Business Layer is responsible for performing our business operation. Here the EJB comes into play.

Persistance Layer is resposible for storing data into the database.



Why We need Ejb in our Business Layer?
                             
              There is lot of answer for this, for simplicty I can say that it helps us to concentrate only on our Business logic, If you are not understand this now don't worry  it will be clear while we seeing  its features.

              There are Several features like TransactionSecurityPortabilityReusability ,Concurrency etc. For the basic understanding we will look into Transactionality

Transactionality:

              Suppose Consider that We are doing transaction from Account A to Account B.

First Operation: What we do in the database side, we debit some amount from Account A
Second Operation: we add that amount into Account B Holder Account ,

Just assume that after performing the First Operation some problem has occured In this situation Account B won't gets amount debited from Account A,then it is totally wrong rite????????

How We can handle this situation?

               Solution: First Operation need to be roll back,We can write our own logic for this but it is programmer burden.To Reduce the burden EJB provides set of the API's which handle this situation.

I hope your doubt got cleared  for the line Concentrate only on Business Logic.

Java Enterprise Application are web-enabled and java based which tells that write once and run in any java based server.

While talking about server,Question comes to our mind, In Which server I should deploy my application, Either Application Server or Web-server.

Application Server is the place where we should deploy our application.

Why Application Server for EJB?
                Applicaton Server contains EJB Container which supports  features like transaction,security,portability,reusability etc

What is EJB Container?
                Ejb container is nothing but the predefined set of API's (usually called as Ejb Components) which help us to provide all the Ejb features for our business layer.


I hope it is Informative:-)

In  Next Blog We will see Types of EJB Components...........