Thursday, February 12, 2009

Interpreter Design Pattern:

This pattern provides a definition of macro language or syntax and parsing into objects in a program. You use this pattern when you need your own parser generator. It is also used when you have to translate a specific expression or when you need to handle a tree related information.

Proxy Design Pattern

Proxy is not a new term for a person like me who has dubious record in school days in terms of attendence. Me and my similar thinking friends were helpful for each other in giving attendence. When one of us would be absent, other will give his attendence. This other person is called a proxy for the original one who is absent in the class and enjoying good times. Thus proxies acts as a place holder for original object.

Example:
1) Using Java XML Pack, you use proxies to access web services with JAX-RPC
2) Loading image icon which is taking time, we first contruct a frame for it using proxy object and later load image.

Facade Design Pattern:

Facade means concealment or hiding the details. Facade pattern make a complex system simpler for the client by providing a unified or general interface which at a higher level to these subsystems. Facade pattern gives an easy entry point to an otherwise complex system.

Example:
JDBC design:
A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients.

Builder Design Pattern:

Process of step by step construction of complex object using simple objects. The Builder pattern allows a client object to construct a complex object by specifying only its type and content. The client is shielded from the details of the objects construction. It gives a finer control to the client over construction of the object.

Abstract Factory Design Pattern

Abstract Factory Design Pattern:
In the Factory design pattern, there is a Factory class which create objects. Simply speaking Factory class is the factory of objects. Abstract Design Pattern is one level above the Factory design pattern and provides Factory of factory. Thus Abstract Factory Design Pattern is used to return one of several factories.

Examples:
In java 1.2, the pluggable look-and-feel classes accomplish this at the system level so that instances of the visual interface components are returned correctly once the program selects the type of look and feel

Factory Design Pattern

Factory Design Pattern:
Factory design pattern is all about having "factory of objects". Here we declare a class (factory) whose job is to instantiate appropriate object out of various objects in parallel hierarchy based on the input given by calling program.

Implementation:
Consider a base class Namer. Suppose it has two subclasses LastFirst and FirstFirst. Then we have a factory class NameFactory. The factory class instantiates either LastFirst or FirstFirst depending upon the String name parameter received from the client.

public class Namer
{
private String firstName;
private String lastName;
public String getFirst()
{
return firstName;
}
public String getLast()
{
return lastName;
}
}

public class FirstFirst extends Namer
{
pubic FirstFirst(String s)
{
int i = s.lastIndexOf(" ");
if(i > 0)
{
firstName = s.substring(0,i).trim();
lastName = s.substring(i+1).trin();
}
else
{
firsName = "";
lastName = s;
}
}
}

public class SecondFirst extends Namer
{
public SecondFirst(String s)
{
int i = s.indexOf(",");
lastName = s.substring(0,i).trim();
firstName = s.substring(i+1).trim();
}
}

class NameFactory
{
public static Name getNamer(String name)
{
int i = name.indexOf(",");
if(i > 0)
{
return new LastFirst(name);
}
else
{
return new FirstFirst(name);
}
}

class Client
{
NameFactory.getNamer(shakil,shahnawaz).getFirst();
NameFactory.getNamer(shakil,shahnawaz).getLast();
}


As we can see in the above example, client is printing the first and last name without knowing which class is being called by the factory class.

Examples of Factory Design Pattern:
1) COM Application
The factory role is poayed by IClassFactory
2) Standard Template Library (STL)
3) EJB:
Creation of entity beans
4) CORBA
CosNaming.Factory plays the role of factory.

Adapter Design Pattern

Adaper Design Pattern or Wrapper Pattern:
Adapter is not a new word in english dictionary. You use adapter to connect your laptop with the electric socket. You can view your laptop as a class and the electric socket as an interface. Your laptop (class) wants to get some functionality via the interface (electric socket) but it does not understand this interface (electric socket). In other words you can say that laptop and electric sockets are incompatible. To make them compatible you require adapter.
Thus adapter design patter convert the existing interface (electric socket) into an interface(adapter) which the client(laptop) can understand. Thus Adapter design pattern achieves compatibility and reusability of the unrelated classes in an application.

Examples of Adapter Design Pattern:
The famous adapter classes in Java API are WindowAdapter, ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter

Singleton Design Pattern

Singleton Pattern:
This pattern is used to ensure that only one instance of a class is created which is accessible globaly in an application.

Implementation:
The definition of singleton pattern is probably the easiest among all design patterns. However its implementation requires a bit of care, as we will see here. Consider the below code:

Program 1:
public class MySingleton{
private static MySingleton instance = null;
private MySingleton() //This constructor will ensure that default constructor is not created
{
}
public static MySingleton getInstance()
{
if(instance == null)
{
instance = new MySingleton();
}
return instance;
}
}


Here we are declaring MySingleton as static to make it available globaly in an application. The constructor is declared as private so that any client creatin object of this class is bound to call getInstance() function instead of calling the constructor. Inside the getInstance() method we are creating the instance of MySingleton only if the instance is null. Thus once an instance is created, other instances of MySingleton class cannot be created.
Above implementation of Singleton pattern is correct to a large extent. However this implemenation may fail in certain scenarios as following:
1) If class is loaded by different classloaders.
2) If a Singleton object is serialized and then subsequently deserialized
3) If two "threads" call getInstance() method at the same time.

Here we will ignore the first two scenarios because I want to give you an opportunity to do research. Now let us consider the third scenario. I think by the time you have read these lines, and if you are a true Java nerd, your suggestion should be ready. The obvious suggestion is simply synchronise the method getInstance() something as following:

Program 2:
public class MySingleton{
private static MySingleton instance = null;
private MySingleton() //This constructor will ensure that default constructor is not created
{
}
public synchronized static MySingleton getInstance()
{
if(instance == null)
{
instance = new MySingleton();
}
return instance;
}
}


Brilliant !! ... so the issue is resolved and we have just implemented a singleton design pattern which is thread safe.
Though above implementation is thread safe but synchronisation is very expensive thing to do as far as performance is concerned. There is an easy and performance wise better approach to do this. See Program 3:

Program 3:

public class MySingleton{
public final static MySingleton instance = new MySingleton();
private MySingleton()
{
}
}


Since static member variables are guaranteed to be created, the first time they are accessed, so this implementation is thread safe. Both Program 2 and Program 3 have there own advantages/disadvantages. Program 2 is performance wise not good but it gives flexibility of changing the number of allowable instances. Suppose later you decided that i should allow three instances of this object to be created, all you will need is a change in the if condition of Program 2 without touching the client side program. Program 3 does not give this flexibility. But as we know when it comes to performance then Program 3 has a definite edge.

Examples of Singleton Design Pattern:
1) One file system, one window manager, one printer spooler, one Test engine, one I/O socket etc
2) Java serial port package viz javax.comm

Tuesday, February 10, 2009

EJB Basics

Enterprise Java Beans:
EJB is both a set of specifications (often called contract) and API. Any application server which is EJB conformant should follow this specification and provide implementation to the API.

What is the use of EJB?
Suppose you have to develop a huge distributed application having complex business logics. While developing such an application you need to take care of several factors like security, transaction management, Remote method invocation, Threading, system management etc to name a few. Thanks to application servers which take care of all these issues. This is possible because these application servers follow certain specifications. If this specification is EJB specification then they are called EJB conformant application servers (e.g. BEA Weblogic, IBM websphere). Further they also support EJB API and all you need to do is to call or override the required functions. Thus you can see that EJB simplifies the development of business component. However if your application is very small having very less business logic then using EJB is not a good idea. The purpose of using EJB is to simplify the development of complex distributed business components and not to increase the complexity of simple business components!!

Types of EJB:
1) Session Bean
a) Stateful
b) Stateless
2) Entity Bean
a) Container managed persistence
b) Bean managed persistence
3) Message Driven Bean

Session Beans:
You write business logic in session bean.
Non persistent
Short lived – life terminates with the termination of client
It is non sharable i.e. it can have only one client at a time.

Stateless Session Bean:
Stateless session beans, as the name suggests, don’t maintain state information.
Because these beans don’t contain state information, same been can be used by more than one client (but one client at a time)
Stateless session beans can be pooled by the container
Since stateless session beans can support multiple clients the offer better scalability
Since stateless session beans are never written to secondary storage, they give better performance.
They can implement web service.

Writing Stateless Session bean:
Step 1:
Write the Remote interface:

ShakilRemote.java (Remote interface)

import javax.ejb.*;
import java.rmi.RemoteException;
import java.rmi.Remote;

public interface ShakilRemote extends EJBObject{

public String hello()throws RemoteException;
}

Step 2:
Write Home interface:

HelloHome.java (Home interface)
import javax.ejb.*;
import java.rmi.RemoteException;

public interface ShakilHome extends EJBHome{
Hello create() throws RemoteException,CreateException;
}

Step 3:
Write the stateless Session bean


ShakilBean.java (stateless session bean)

import javax.ejb.*;
public class ShakilBean implements SessionBean
{
private SessionContext ctx;
public void ejbCreate()
{
System.out.println("inside ejbCreate");
}
public void ejbRemove(){
System.out.println("inside ejbRemove");
}
public void ejbActivate(){
System.out.println("inside ejbActivate");
}
public void ejbPassivate(){
System.out.println("inside ejbPassivate");
}
public void setSessionContext(SessionContext ctx){
System.out.println("inside setSessionContext()");
}
public String hello()
{
System.out.println("Hello world");
}

}

Step 4:
Create ejb-jar.xml