Design Pattern in Java
Design Pattern in Java
Java
Programming
(J2EE)
Factory Method Design Pattern
A factory method pattern is a creational pattern. It is used to instantiate an object from one
among a set of classes based on a logic.
Assume that you have a set of classes which extends a common super class or interface.
Now you will create a concrete class with a method which accepts one or more arguments.
This method is our factory method. What it does is, based on the arguments passed factory
method does logical operations and decides on which sub class to instantiate. This factory
method will have the super class as its return type. So that, you can program for the
interface and not for the implementation. This is all about factory method design pattern.
package com.javapapers.sample.designpattern.factorymethod;
}
First subclass:
package com.javapapers.sample.designpattern.factorymethod;
}
Builder Design Pattern
Builder pattern is used to construct a complex object step by step and the final step will
return the object. The process of constructing an object should be generic so that it can be
used to create different representations of the same object.
Following is the interface for which the factory implementation should be done. Inturn all
abstract factory will return this type.
package com.javapapers.sample.designpattern.abstractfactory;
Builder interface. We will have multiple different implementation of this interface in order
to facilitate, the same construction process to create different representations.
package com.javapapers.sample.designpattern.builder;
public IglooHouseBuilder() {
this.house = new House();
}
public void buildBasement() {
house.setBasement("Ice Bars");
}
public TipiHouseBuilder() {
this.house = new House();
}
Following class constructs the house and most importantly, this maintains the building
sequence of object.
package com.javapapers.sample.designpattern.builder;
engineer.constructHouse();
It’s a simple and straight forward design pattern. Nothing much hidden beneath it. If you
don’t have much experience with enterprise grade huge application, you may not have
experience in creating a complex / time consuming instance. All you might have done is use
the new operator or inject and instantiate.
If you are a beginner you might be wondering, why all the fuss about prototye design
pattern and do we really need this design pattern? Just ignore, all the big guys requires it.
For you, just understand the pattern and sleep over it. You may require it one day in future.
Prototype pattern may look similar to builder design pattern. There is a huge difference to it.
If you remember, “the same construction process can create different representations” is
the key in builder pattern. But not in the case of prototype pattern.
So, how to implement the prototype design pattern? You just have to copy the existing
instance in hand. When you say copy in java, immediately cloning comes into picture. Thats
why when you read about prototype pattern, all the literature invariably refers java cloning.
Simple way is, clone the existing instance in hand and then make the required update to the
cloned instance so that you will get the object you need. Other way is, tweak the cloning
method itself to suit your new object creation need. Therefore whenever you clone that
object you will directly get the new object of desire without modifying the created object
explicitly.
The prototype design pattern mandates that the instance which you are going to copy
should provide the copying feature. It should not be done by an external utility or provider.
But the above, other way comes with a caution. If somebody who is not aware of your
tweaking the clone business logic uses it, he will be in issue. Since what he has in hand is not
the exact clone. You can go for a custom method which calls the clone internally and then
modifies it according to the need. This will be a better approach.
Always remember while using clone to copy, whether you need a shallow copy or deep
copy. Decide based on your business needs. If you need a deep copy, you can use
serialization as a hack to get the deep copy done. Using clone to copy is entirely a design
decision while implementing the prototype design pattern. Clone is not a mandatory choice
for prototype pattern.
In prototype pattern, you should always make sure that you are well knowledgeable about
the data of the object that is to be cloned. Also make sure that instance allows you to make
changes to the data. If not, after cloning you will not be able to make required changes to
get the new required object.
Following sample java source code demonstrates the prototype pattern. I have a basic bike
in hand with four gears. When I want to make a different object, an advance bike with six
gears I copy the existing instance. Then make necessary modifications to the copied
instance. Thus the prototype pattern is implemented. Example source code is just to
demonstrate the design pattern, please don’t read too much out of it. I wanted to make
things as simple as possible.
A java beginner will know about singleton design pattern. At least he will think that he
knows singleton pattern. The definition is even easier than Newton’s third law. Then what is
special about the singleton pattern. Is it so simple and straightforward, does it even deserve
an article? Do you believe that you know 100% about singleton design pattern? If you
believe so and you are a beginner read through the end, there are surprises for you.
There are only two points in the definition of a singleton design pattern,
1. There should be only one instance allowed for a class and
2. We should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it.
[GoF, p127]“.
The key is not the problem and definition. In singleton pattern, trickier part is
implementation and management of that single instance. Two points looks very simple, is it
so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the
flexibility of the APIs and many flexible ways available to access an instance. Implementation
is very specific to the language you are using. So the security of the single instance is specific
to the language used.
package com.javapapers.sample.designpattern;
public class Singleton {
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
You need to be careful with multiple threads. If you don’t synchronize the method which is
going to return the instance then, there is a possibility of allowing multiple instances in a
multi-threaded scenario. Do the synchronization at block level considering the performance
issues. In the above example for singleton pattern, you can see that it is thread-safe.
Early and lazy instantiation in singleton pattern
The above example code is a sample for lazy instantiation for singleton design pattern. The
single instance will be created at the time of first call of the getSingleInstance() method. We
can also implement the same singleton design pattern in a simpler way but that would
instantiate the single instance early at the time of loading the class. Following example code
describes how you can instantiate early. It also takes care of the multithreading scenario.
package com.javapapers.sample.designpattern;
public class Singleton {
private static Singleton singleInstance = new Singleton();
private Singleton() {}
public static Singleton getSingleInstance() {
return singleInstance;
}
}
This article is an attempt to explain the basics on singleton design pattern. If you want more
insight on singleton refer this technical article “When is a Singleton not a Singleton?” and its
references.
An adapter helps two incompatible interfaces to work together. This is the real world
definition for an adapter. Adapter design pattern is used when you want two different
classes with incompatible interfaces to work together. The name says it all. Interfaces may
be incompatible but the inner functionality should suit the need.
In real world the easy and simple example that comes to mind for an adapter is the travel
power adapter. American socket and plug are different from British. Their interfaces is not
compatible with one another. British plugs are cylindrical and American plugs are
rectangularish. You can use an adapter in between to fit an American (rectangular) plug in
British (cylindrical) socket assuming voltage requirements are met with.
Remote Proxy:
Sometime back I wrote an article on a hello-world for Soap Web Service. A part of it
contains implementation of proxy design pattern. The client has the stub files generated
which acts as a proxy for the classes in server side.
package com.javapapers.designpattern.proxy;
}
package com.javapapers.designpattern.proxy;
public class Lion implements Animal {
}
package com.javapapers.designpattern.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;