Search This Blog

Wednesday 25 January 2017

Factory Design Pattern in Java

Factory Design Pattern in Java
Intent
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Motivation
Factory Design pattern is also known as Virtual Constructor, the Factory Method is related to the idea on which libraries work: a library uses abstract classes for defining and maintaining relations between objects. One type of responsibility is creating such objects.
The library knows when an object needs to be created, but not what kind of object it should create, this being specific to the application using the library.

The Factory method works just the same way: it defines an interface for creating an object, but leaves the choice of its type to the subclasses, creation being deferred at run-time.

 A simple real life example of the Factory Method is the Bank Account.
A user wants to open an Account in a bank.  A user can open either a Saving Account, Current Account, Salary Account,  Demat Account based on their requirement.
Depending on the requirement the subclass object for any of the account type can be created can be created.

Applicability
Use the Factory Method pattern when
  •          A class can't anticipate the class of objects it must create.
  •          A class wants its subclasses to specify the objects it creates.
  •          Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


Consequences
  •          Factory methods eliminate the need to bind application-specific classes into your code.
  •           Provides hooks for subclasses. Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of an object.
  •          Connects parallel class hierarchies. Parallel class hierarchies result when a class delegates some of its responsibilities to a separate class.

 Implementation
We're going to create an Account interface and concrete classes implementing the Account interface.
A factory class AccountFactory would be responsible for returning object.
FactoryPatternDemo  class will use AccountFactory to get an Account object.
It will pass information (Saving / Current / Salary / Demat) to AccountFactory to get the type of object it needs.
Create an Interface Account
public interface Account {
      public void openAccount();
}

Create Classes SavingAccount, SalaryAccount, CurrentAccount, DematAccount which implements the Account interface.
public class SavingAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Savings Account");
      }
}

public class CurrentAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Current Account"); 
      }
}

public class SalaryAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Salary Account");
      }
}

public class DematAccount implements Account{

      @Override
      public void openAccount() {
            System.out.println("Opening Demat Account");   
      }
}

Create the AccountFactory Class which returns Objects of the Subclasses.
public class AccountFactory {
public Account getAccountType(String accountType){
      if(accountType==null){
            return null;
      }
            if(accountType.equalsIgnoreCase("saving")){
                  return new SavingAccount();
            }
            else if(accountType.equalsIgnoreCase("current")){
                  return new CurrentAccount();
            }
            else if(accountType.equalsIgnoreCase("salary")){
                  return new SalaryAccount();
            }
            else if(accountType.equalsIgnoreCase("demat")){
                  return new DematAccount();
            }
      return null;     
}
}

Create the FactoryPatternDemo with the main method
public class FactoryPatternDemo {
public static void main(String[] args) {
      AccountFactory accountFactory=new AccountFactory();
     
      Account saving=accountFactory.getAccountType("saving");
      saving.openAccount();
     
      Account current=accountFactory.getAccountType("current");
      current.openAccount();
     
      Account salary=accountFactory.getAccountType("salary");
      salary.openAccount();
     
      Account demat=accountFactory.getAccountType("demat");
      demat.openAccount();
}
}

Execute the above class , we get the following output.


Factory Design Pattern in Java
Factory Design Pattern in Java













Monday 23 January 2017

Difference Between Servlet and JSP

This post highlights the difference between JSP and Servlet technologies.

Java Servlet technology and JavaServer Pages (JSP pages) are server-side technologies that become the standard way to develop web applications.

Most importantly, if used effectively by following best practices, servlets and JSP pages help separate presentation from content.

Servlets support a request and response programming model. When a client sends a request to the server, the server sends the request to the servlet. The servlet then constructs a response that the server sends back to the client. When a client request is made, the service method is called and passed a request and response object. The servlet first determines whether the request is a GET or POST operation. It then calls one of the following methods: doGet or doPost. The doGet method is called if the request is GET, and doPost is called if the request is POST.

Adding more, Servlets are Java classes that can generate dynamic HTML content using print statements.
out.println("<html><head><title>"+thisIsMyMessage+"</title></head>");
So, you can embed HTML code into Java code.

A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a JSP page is .jsp rather than .html or .htm, which tells the server that this page requires special handling that will be accomplished by a server extension. When a JSP page is called, it will be compiled (by the JSP engine) into a Java servlet.

Importantly, we can add dynamic content or Java Code inside an HTML Tag using JSP’s Scriplets.
And scriptlets, this is code fragments like:
<% String message = "Hello !"%>
<H2> Welcome and  <%=message%>! </H2>
So, you can embed Java code into HTML code.





SERVLET
JSP
A servlet is a server-side program and written purely on Java.
JSPs are HTML pages with .jsp extension. JSP’s are extension of servlets to minimize the effort of developers to write User Interfaces using Java programming.
Executes inside a Web server, such as Tomcat
A JSP program is compiled into a Java servlet before execution. Once compiled into a servlet, it's life cycle will be same as of servlet. But, JSP has it's own API for the lifecycle.
Servlets run faster than JSP
JSP runs slower because it has the transition phase for converting from JSP page to a Servlet file.
Servlet has the life cycle methods init(), service() and destroy()
JSP has the life cycle methods of jspInit(), _jspService() and jspDestroy()
Difficult to write as one has to write HTML tags within quotes(“<HTML>”) in Java. Mixing HTML content inside Java is tedious.
Easier to write than servlets as it is similar to HTML
Written in Java, with a few additional APIs specific to this kind of processing. Since it is written in Java, it follows all the Object Oriented programming techniques.
One of the key advantage is we can build custom tags using JSP API ,  which can be available as the re-usable components with lot of flexibility
In MVC architecture Servlet acts as controller.
In MVC architecture JSP acts as view.
Servlet advantages include:
·  Performance: get loaded upon first request and remains in memory indefinitely.
·  Simplicity: Run inside controlled server environment.
·  Session Management : overcomes HTTP's stateless nature
·  Java Technology : network access, Database connectivity, j2ee integration
JSP Provides an extensive infrastructure for:
·         Tracking sessions.
·         Managing cookies.
·         JSP is Extensible: Can create custom tags to extend the JSP functionality.
·         Separation of roles: Clearly identifies separation of roles for Developers, Content Authors/ Graphic Designers/ Web Masters.

Friday 20 January 2017

Strings in switch statements


Design Pattern

What's New in Java 8

Java Platform, Standard Edition 8 is a major feature release. Java 8 contains a large number of new features. Although all are important, the three most important one are:
  • Lambda expressions
  • The stream API in java.util.stream
  • Default interface methods

Lambda Expressions
The most important new Java 8 feature is the lambda expression.
Lambda expressions are very important as they add functional programming features to Java. Lambda expressions can simplify and reduce the amount of source code needed to create certain constructs, such as some types of anonymous classes. This is particularly helpful when implementing a number of commonly used event handlers.
To support lambda expressions Java has been expanded by the inclusion of a new operator (the –>) and a new syntax element.


To understand the benefits that lambda expressions bring, consider the following ActionEvent handler, which uses the traditional, anonymous class, approach:

myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
myLabel.setText("Button pressed.");
}
});

With JDK 8, this event handler can be written using a lambda expression

myButton.addActionListener(
(ae) -> myLabel.setText("Button pressed.")
);


As we observe code is shorter, that is more direct and to the point.



The Stream API
Another important feature of Java 8 is the new stream API, which is packaged in java.util.stream.
A stream represents a sequence of data. The key aspect of the stream API is its ability to perform pipeline operations that search, filter, map, or otherwise manipulate data.

Let’s assume we have a list that stores employee names, department, e-mail and phone numbers. Using the stream API, we can efficiently pipeline the operations that search for entries that match some criterion, for example department name, sort the matching items, and then extract only the e-mail addresses In many cases, such actions can be performed in parallel, thus providing a high level of efficiency. The stream API provides a powerful means of handling data in an efficient, yet easy to use way.

Default Methods
With the release of Java 8, it is now possible for an interface method to define a default implementation. This new capability is called the default method.

Default method enables us a means by which interfaces could be expanded without breaking pre-existing code.
In simple terms default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.


When a non-abstract class implements an interface, it must implement all methods defined by that interface. If a new method is to an existing interface, then the addition of that method would break pre-existing code, because no implementation would be found for that new method in pre-existing classes. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus, the addition of a default method will not cause pre-existing code to break. This enables interfaces to be gracefully evolved over time without negative consequences.