Search This Blog

Friday 17 February 2017

Abstract Factory Design Pattern in Java

Intent
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Motivation
Abstract Factory patterns work around a super-factory which creates other factories.  This factory is also called as factory of factories and comes under Creational pattern. The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.
In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn't know which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.
This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.


Applicability
Use the Abstract Factory pattern when
Ø  A system should be independent of how its products are created, composed, and represented.
Ø  A system should be configured with one of multiple families of products.
Ø  A family of related product objects is designed to be used together, and you need to enforce this constraint.
Ø  You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Consequences
The Abstract Factory pattern has the following benefits and liabilities:
Ø  It isolates concrete classes. The Abstract Factory pattern helps you control the classes of objects that an application creates.
Ø  It makes exchanging product families easy. The class of a concrete factory appears only once in an application—that is, where it's instantiated.
Ø  It promotes consistency among products. When product objects in a family are designed to work together, it's important that an application use objects from only one family at a time.
Ø  Supporting new kinds of products is difficult. Extending abstract factories to produce new kinds of Products isn't easy.



Implementation
1.      Create a class Car

public abstract class Car {

   public abstract String getHorsePower();
   public abstract String getSeatingCapacity();
   public abstract String getMileage();
  
   @Override
   public String toString() {
   return "Horse Power : " + this.getHorsePower() +
   ", Seating Capacity : "+this.getSeatingCapacity() +  
         ", Mileage : "+this.getMileage();
   }
}

2.      Create sub class Sedan of class Car
public class Sedan extends Car{

   private String horsePower;
   private String seatingCapacity;
   private String mileage;
  
public Sedan(String horsePower, String seatingCapacity, String mileage) {
         this.horsePower = horsePower;
         this.seatingCapacity = seatingCapacity;
         this.mileage = mileage;
   }

   @Override
   public String getHorsePower() {
         return this.horsePower;
   }

   @Override
   public String getSeatingCapacity() {
         return this.seatingCapacity;
   }

   @Override
   public String getMileage() {
         return this.mileage;
   }

}




3.      Create another sub class SUV of class Car
public class SUV extends Car{
   private String horsePower;
   private String seatingCapacity;
   private String mileage;
  
public SUV(String horsePower, String seatingCapacity, String mileage) {
         super();
         this.horsePower = horsePower;
         this.seatingCapacity = seatingCapacity;
         this.mileage = mileage;
   }

   @Override
   public String getHorsePower() {
         return this.horsePower;
   }

   @Override
   public String getSeatingCapacity() {
         return this.seatingCapacity;
   }

   @Override
   public String getMileage() {
         return this.mileage;
   }
}

4.      Create Abstract factory interface  (Notice that the createCar() method returns an instance of super class Car)
public interface CarAbstractFactory {
   public Car createCar();
}

5.      Now we will create Factory class for Each sub class i.e SedanFactory and SUVFactory class
public class SedanFactory implements CarAbstractFactory{

   private String horsePower;
   private String seatingCapacity;
   private String mileage;

   public SedanFactory(String horsePower, String seatingCapacity, String mileage) {
         this.horsePower = horsePower;
         this.seatingCapacity = seatingCapacity;
         this.mileage = mileage;
   }
         @Override
   public Car createCar() {
         return new Sedan(horsePower,seatingCapacity,mileage);
   }
}

public class SUVFactory implements CarAbstractFactory{

      private String horsePower;
      private String seatingCapacity;
      private String mileage;

      public SUVFactory(String horsePower, String seatingCapacity, String mileage) {
            this.horsePower = horsePower;
            this.seatingCapacity = seatingCapacity;
            this.mileage = mileage;
      }
     
      @Override
      public Car createCar() {
            return new SUV(horsePower,seatingCapacity,mileage);
      }
}

6.      Create a class that will provide the entry point for the client classes to create sub-classes.
public class CarFactory {
public static Car getCar(CarAbstractFactory factory){
   return factory.createCar();
}
}

7.      Write a class with the main() to test your code.
public class Main {
public static void main(String[] args) {
Car sedan=CarFactory.getCar(new SedanFactory("2.2", "5", "15 KMPL"));
   System.out.println("Details of Sedan : "+sedan);
  
   Car suv=CarFactory.getCar(new SUVFactory("3.5", "07", "12 KMPL"));
   System.out.println("Details of SUV : "+suv);
}
}


We will get the following output.

Abstract Factory Design Pattern
Abstract Factory Design Pattern 

Wednesday 15 February 2017

Java Servlet Life Cycle

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

Servlet Life Cycle

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.
1.      If an instance of the servlet does not exist, the web container
a.      Loads the servlet class.
b.      Creates an instance of the servlet class.
c.       Initializes the servlet instance by calling the init method.
2.      Invokes the service method, passing request and response objects.
3.      If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy method.

Lets try to understand the Servlet Life Cycle in details

1.      A web browser sends an HTTP request to a web server by any one of the following ways.
a.      A user clicks on a hyperlink displayed in an HTML page.
b.      A user fills out a form in an HTML page and submits it.
c.       A user enters a URL in the browser’s address field and presses Enter.

2.      The container "sees" that the request is for a servlet, so the web container creates two objects.
a.      HttpServletRequest
b.      HttpServletResponse

3.      The Web Container finds the correct servlet based on the URL in the request , the container then creates or allocate a thread for that request and calls the service() method of the servlet, passing the request and response objects as arguments.

4.      The service() method figures out which servlet method to call based on HTTP method sent by the client.If the client sent GET , then corresponding doGet() method is called.

5.      The servlet uses the response object to write the response to the client.

6.      The service() method completes, the threads dies or returns to  back to the pool.The request and response object are garbage collected.The client gets the response.



Servlet Life Cycle

Servlet Life Cycle


Monday 13 February 2017

Bean scopes

Bean scopes in Spring

When we create a bean definition, we are actually creating is actual instances of the class defined by that bean definition. You can control the various dependencies and configuration values along with the scope of the objects created from a particular bean definition. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports five scopes of which three are available only if you are using a web-aware ApplicationContext.


Scope
Description
singleton
A single bean definition to a single object instance per Spring IoC container.
prototype
A single bean definition to any number of object instances.
request
A single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session
A single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session
A single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.


The singleton scope
The singleton scope is the default scope in Spring. For a singleton bean, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
When you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

The prototype scope

Prototype scope of bean will create a new bean instance every time a request for that specific bean is made. You should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.
When deploying a bean in the prototype scope, please take note that , Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. This means that while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called. It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto.

The request scope

The Spring container will create a brand new instance of the bean definition for each and every HTTP request. You can change the internal state of the instance that is created as much as you want. When the request is finished processing, the bean that is scoped to the request will be discarded.

The session scope

The Spring container will create a brand new instance of the  bean using the bean definition for the lifetime  of a single HTTP Session. In other words, the bean will be effectively scoped at the HTTP Session level. Just like request-scoped beans, you can change the internal state of the instance that is created. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session will also be discarded.

The global session scope

The global session scope is similar to the HTTP Session scope, and makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared amongst all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are scoped to the lifetime of the global portlet Session.


Bean scopes
Bean scopes

Thursday 9 February 2017

Autowiring In Spring

It is possible to automatically let Spring framework resolve dependencies for the bean by inspecting contents of the BeanFactory. This is kown as Autowiring.  A BeanFactory is able to autowire relationships between collaborating beans.
The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans won't be autowired.
Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, saving a significant amount of typing. In an XmlBeanFactory, the autowire mode for a bean definition is specified by using the autowire attribute of the bean element.






Some advantages of autowiring:
  • It can reduce the volume of configuration required.
  • It can cause configuration to keep itself up to date as your objects evolve. For example, if you need to add an additional dependency to a class, that dependency can be satisfied automatically without the need to modify configuration.
Some disadvantages of autowiring:

  • Wiring information may not be available to tools that may generate documentation from a Spring application context.
  • Autowiring by type will only work when there is a single bean definition of the type specified by the setter method or constructor argument. You need to use explicit wiring if there is any potential ambiguity.
Autowiring In Spring
Autowiring In Spring