Saturday, February 5, 2011


Creational Patterns - Singleton Pattern
This is one of the most commonly used patterns. There are some instances in the application where we have to use just one instance of a particular class. Let’s take up an example to understand this.
A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is started.
package creational.singleton;
import org.apache.log4j.Priority;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Properties;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.IOException;

public class Logger {

private String fileName;
private Properties properties;
private Priority priority;
/**
* Private constructor
*/
private Logger() {
    logger = this;
}
/**
* Level of logging, error or information etc
*
* @return level, int
*/
public int getRegisteredLevel() {
      int i = 0;
      try {
             InputStream inputstream =  getClass().getResourceAsStream("Logger.properties");
            properties.load(inputstream);
            inputstream.close();
            i = Integer.parseInt(properties.getProperty("**logger.registeredlevel**"));
      if(i < 0 || i > 3)
            i = 0;
      }
      catch(Exception exception) {
            System.out.println("Logger: Failed in the getRegisteredLevel method");
            exception.printStackTrace();
      }
      return i;
}
/**
* One file will be made daily. So, putting date time in file
* name.
*
* @param gc GregorianCalendar
* @return String, name of file
*/
private String getFileName(GregorianCalendar gc) {
      SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MMM-yyyy");
      String dateString = dateFormat1.format(gc.getTime());
      String fileName = "d:/shail/patterns/logs/Log-" + dateString + ".txt";
      return fileName;
}
/**
* A mechanism to log message to the file.
*
* @param p Priority
* @param message String
*/
public void logMsg(Priority p, String message) {
try {
      GregorianCalendar gc = new GregorianCalendar();
      String fileName = getFileName(gc);
      FileOutputStream fos = new FileOutputStream(fileName, true);
      PrintStream ps = new PrintStream(fos);
      SimpleDateFormat dateFormat2 = new SimpleDateFormat("EEE, MMM d, yyyy 'at' hh:mm:ss a");
      ps.println("<"+dateFormat2.format(gc.getTime())+">["+message+"]");
      ps.close();
}
catch (IOException ie) {
      ie.printStackTrace();
}
}
/**
* this method initialises the logger, creates an object
*/
public static void initialize() {
      logger = new Logger();
}
// singleton - pattern
private static Logger logger;
public static Logger getLogger() {
      return logger;
}
}// End of class
Difference between static class and static method approaches:
One question which a lot of people have been asking me. What’s the difference between a singleton class and a static class? The answer is static class is one approach to make a class “Singleton”.
We can create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.
Example:
final class Logger {
//a static class implementation of Singleton pattern
      static public void logMessage(String s) {
            System.out.println(s);
      }
}// End of class
//==============================
public class StaticLogger {
      public static void main(String args[]) {
            Logger.logMessage("This is SINGLETON");
      }
}// End of class
The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.


Creational Patterns - Factory Pattern
Factory of what? Of classes. In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.

Let’s take an example to understand this pattern.

Example: Let’s suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr. <Name> and if the sex is Female (F), it displays message saying Hello Ms <Name>.

The skeleton of the code can be given here.

public class Person {
public String name;
private String gender;
public String getName() {
     return name;
}

public String getGender() {
     return gender;
}
}// End of class
This is a simple class Person having methods for name and gender. Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen.
public class Male extends Person {
      public Male(String fullName) {
           System.out.println("Hello Mr. "+fullName);
     }
}// End of class

Also, the class Female
public class Female extends Person {
public Female(String fullNname) {
     System.out.println("Hello Ms. "+fullNname);
}
}// End of class
Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided.

public class SalutationFactory {

public static void main(String args[]) {
       SalutationFactory factory = new SalutationFactory();
       factory.getPerson(args[0], args[1]);
}
public Person getPerson(String name, String gender) {
       if (gender.equals("M"))
            return new Male(name);
       else if(gender.equals("F"))
            return new Female(name);
       else
            return null;
}
}// End of class
This class accepts two arguments from the system at runtime and prints the names.
Running the program: java   Shailendra M
The result returned is: “Hello Mr. Shailendra”.
When to use a Factory Pattern?
The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.

Java Design Pattern

Shailendra kumar shail @ AVACorp.biz
Design Pattern in Java
Abstract: “Pattern” as the name suggests, means series of events occurring in a definite order. The patterns can be found in Java and J2ee technologies also. Many a times, we find that there is a particular way of tackling a problem. This way is easy and has been used many times successfully by a number of people earlier also. This method becomes a pattern.
Learning the design patterns is a multiple step process:
·         Acceptance
·         Recognition
·         Internalization
 “Design patterns are recurring solutions to design problems.”
Patterns: According to commonly known practices, there are 23 design patterns in Java. These patterns are grouped under 3 heads:
1. Creational Patterns
·         Factory
·         Abstract Factory
·         Singleton
·         Builder
·         Prototype
2. Structural Patterns
·         Adapter
·         Bridge
·         Composite
·         Decorator
·         Façade
·         Flyweight
·         Proxy
3. Behavioral Patterns
·         Chain of Responsibility
·         Command
·         Interpreter
·         Iterator
·         Mediator
·         Momento
·         Observer
·         State
·         Strategy
·         Template
·         Visitor