Wednesday, September 25

Template Design Pattern in java , Spring

                                           Template Design Pattern in java , Spring







What is Template Pattern

  – Template pattern is about defining the blueprint of the algorithm wherein some of the steps of the implemented in base class and others are deferred for subclass to implement. Spring framework implemented this pattern for many features like, JmsTemplate, JDBCTemplate.



Example:







&lt bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype" &gt
 &lteq bean &gt



Let's understand Template Design Pattern form core java perspective :





public abstract class ProjectManager {



public final void  collectRequirement(){

   

    System.out.println("requirements are gathered same way in all technology projects. So this could be implemented in baseclass itself and otehr classes can inherit it as it is.");

}



public  abstract void developDesign();



public  abstract void developCode();



public  final void assessQuality(){

    System.out.println("Quality is assessed in same way in all technology projects. So this could be implemented in baseclass itself and otehr classes can inherit it as it is.");

}

public  abstract void deploy();



}


ProjectManager  is abstract class. It has both abstract and implemented methods. Generic methods are implemented here while specific methods are kept abstract for implementing class to define them

Generic method are kept final So that they are not overriden and logic defined in them is used as it is in all implementations.   



  class JavaProjectManager extends ProjectManager {



    @Override

    public void developDesign() {

       

        System.out.println("Desiging is done here in JAVA way");

        // TODO Auto-generated method stub

       

    }



    @Override

    public void developCode() {

       

        System.out.println("Coding is done here in JAVA way");

        // TODO Auto-generated method stub

       

    }



    @Override

    public void deploy() {

       

        System.out.println("Deployment is done here in JAVA way");

        // TODO Auto-generated method stub

       

    }

   

   

}

JavaProjectManager   is implementation of ProjectManager class. It has defined all the specific methods as per the logic spefic to JavaProjectManager class functional requirement

 

  class MicroSoftProjectManager extends ProjectManager {



      @Override

      public void developDesign() {

         

          System.out.println("Desiging is done here in MicroSoft technology way");

          // TODO Auto-generated method stub

         

      }



      @Override

      public void developCode() {

         

          System.out.println("Coding is done here in  MicroSoft technology way");

          // TODO Auto-generated method stub

         

      }



      @Override

      public void deploy() {

         

          System.out.println("Deployment is done here in  MicroSoft technology way");

          // TODO Auto-generated method stub

         

      }

     

     

  }



-->

Similarly MicroSoftProjectManager is implementation of ProjectManager class. It has defined all the specific methods as per the logic spefic to MicroSoftProjectManager class functional requirement


 

  class mainFramesProjectManager extends ProjectManager {



      @Override

      public void developDesign() {

         

          System.out.println("Desiging is done here in mainFrames technology way");

          // TODO Auto-generated method stub

         

      }



      @Override

      public void developCode() {

         

          System.out.println("Coding is done here in  mainFrames technology way");

          // TODO Auto-generated method stub

         

      }



      @Override

      public void deploy() {

         

          System.out.println("Deployment is done here in  mainFrames technology way");

          // TODO Auto-generated method stub

         

      }

     

     

  }

Similarly mainFramesProjectManager is implementation of ProjectManager class. It has defined all the specific methods as per the logic spefic to MicroSoftProjectManager class functional requirement.

Conclusion
So template method is all about defining the execution steps in a contract , provide implementation for all generic methods in contract itself and let the implementation class implement the specific methods. But template or blueprint for all high level steps is covered in abstract class only irrespective of operation is generic or specific.









Spring framework and Singleton design pattern , Singleton vs prototype , Method injection in Spring

Spring framework and Singleton design pattern , Singleton vs prototype , Method injection in Spring







Singleton design pattern

In spring configuration file , when we define bean scope attributes, value is set as Singleton to instance control the Bean instances to only one instance.

&lt bean id=”manager” class=”com.org.company.Manager” scope="singleton” &gteq


In above definition Manager is defined as singleton

But one should note that spring here defines the singleton only in scope of current application-context . So concept of singleton per application Context is followed in spring . If same class is loaded in two different application-context two instances will be created , one for each application context.


Scope attribute can have below values

singleton
    Scopes a single bean definition to a single object instance per SpringBeanFactory /applicationContext.

prototype
    One bean per object instance. .

request
       Instance per request . Every  HTTP request will have its own instance created and will live till request is valid.

session
      Instance per session. Every  HTTP session will have its own instance created and will live till request is valid.

global session   
    Scopes a single bean definition to the lifecycle of a global HTTP Session. This is only valid  in case of portlet context.



Also , concept of singleton in spring is different from that of GOF . GOF says singleton means single instance per classloader while spring says single instance per container. BeanFactory or applicationContext is referred as container .

Various ways to define singleton in spring are :

&lt bean id=”manager” class=”com.org.company.Manager” scope="singleton” &gteq
&lt bean id=”manager” class=”com.org.company.Manager” &gteq
&lt bean id=”manager” class=”com.org.company.Manager” singleton="true" &gteq
Default scope of bean is singleton. So if scope attribute is not define Bean is automatically singleton.


So question arise : Where to use singleton and where to use prototype

How can you decide that ?

 State of the instance can be used to decide that. Singleton bean is shared among multiple request So data is shared here . Means If data is a request specific and does not require sharing  , we can not go with singleton approach as with that approach we won't be able to maintain different states for different beans of same class. Conclusively As a rule of thumb We should be governed by rule : for stateful bean we should defined it with prototype (each bean instance will have its own copy with its own data) . For stateless bean we can define it as singleton scoped as in that case bean does not maintain any request specific state and can be shared among multiple request to cater a set of common behavior and shared data.


If we say

&lt bean id=”manager” class=”com.org.company.Manager” singleton="false" &gteq
It is prototype


OR If we say 

& ltbean id=”manager” class=”com.org.company.Manager” scope="prototype” &gteq  

It is prototype



One more important thing to know is that a bean in prototype scope has to be explicitly destructed by user code after use . Container does not keep the reference of prototype bean after instantiation . It just create and decorate or assemble the bean ,handle it to client and forget the bean. Now its user code's responsibility to write it's destruction mechanism . So once it is used client code should release it and all heavy objects associated with it.Generally we define bean post-processor method to do that clean up.





If a singleton bean has dependency on prototype bean How It would be resolved if any time a new prototype bean  is required and should be associated with singleton bean . Singleton bean is created once for ever and dependencies are associated at creation time So whatever the dependency (here prototype) will not be updated again and again.

So what is the solution to overcome this



-->

Spring provides concept of method injection .

How does method injection works and resolve this problem ?


Let's understand this with an example :



public abstract class Manager{

   public Object process() {
     
      Develoerdeveloper = retrieveDeveloper();
     

   }

   
   protected abstract Develoer retrieveDeveloper();
}




&lt!--  prototype  -->
&ltbean id="command" class="Develoer" scope="prototype">

&lt/bean>

&ltbean id="manager" class="Manager">
  &ltlookup-method name="retrieveDeveloper" bean="Develoer"&gteq
&lt/bean>

 


What is happening here?

Manager is singleton class here and has a dependency on Developer bean , which is defined as prototype bean.So Developer needs to be loaded again and again depending upon changing bean data as Developer is stateful instance.
So we are using here , method injection technique. retrieveDeveloper is lookup method that look up for Developer bean as and when method is invoked and associate the new Developer bean as and when created. Thus keeps the Singleton bean associated with required and updated instance of Developer bean all the time.