Category Archives: Design Patterns

Inject Or Autowired

Sometimes in a Spring framework code, we see the keywords @Inject and @Autowired being used interchangeably. Simply putting it @Autowired is Spring specific annotation for implementing Dependency Injection, whereas @Inject is part of Java EE 6 specification, hence more generic.

JSR 299, Java EE 6 specification, provided a feature called Contexts and Dependency Injection (CDI). http://docs.oracle.com/javaee/6/tutorial/doc/giwhb.html.

JSR 330, more specifically talks about Dependency Injection. https://dzone.com/articles/what-relation-betwe-there

A more elaborated explanation on usage of various DI annotations – http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/#more-2350

Inversion of Control: Dependency Injection vs Dependency Lookup

Inversion of Control is a principle which recommends moving unwanted responsibilities out of a class and letting the class focus on core responsibilities, hence providing loose coupling.

There are two basic ways in Java to provide IOC- Dependency Injection and Dependency lookup.

As the name suggest, Dependency Injection is where the dependency is injected from outside the class, and class is not worried about details – http://kamalmeet.com/coding/more-on-dependency-injection/

Dependency lookup is where class itself looks up for dependency and chooses appropriate implementation. Use of JNDI lookup for proper bean of datasource is a good example.

InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(“jndiName”);

Double Check Locking- pattern

Double check locking pattern is used for double checking the condition before acquiring a lock on an object. This helps reducing unneccary locks.

To understand lets take a simple example of creating a singleton object.

public static MySingleton getInstance()
{
if(null==mysingleton)
mysingleton=new MySingleton();
return mysingleton;
}

The challenge with above code is that it is not threadsafe. So we might end up creating multiple objects of MySingleton in case of multithreaded environment. So we will add synchronization.

public static synchronized MySingleton getInstance()
{
if(null==mysingleton)
mysingleton=new MySingleton();
return mysingleton;
}

Though we have saved our code from multi threading, we have added additional load of synchronization, i.e. each thread will have to wait for previous thread to finish processing of this method before entering into it. The actual error case will occur only for first time, i.e. when mysingleton object is null, we would like to stop other threads to execute the block. So to optimiza the code, we will use a technique called double locking.

public static synchronized MySingleton getInstance()
{
if(null==mysingleton)
{
synchronized(MySingleton.class) {
if(null==mysingleton)
mysingleton=new MySingleton();
}
}
return mysingleton;
}

You can see we are applying synchronized block only when we are sure that we are in a case we want to stop multiple threads from going ahead, rather than blocking threads all the time.

http://en.wikipedia.org/wiki/Double-checked_locking

Template method pattern vs Strategy Pattern

Template method pattern and Strategy pattern can appear quite similar in nature as both help us execute an algorithm/ code steps and define executions differently under different circumstances.

The major difference is that Strategy pattern let you decide complete different strategy i.e. set of algorithm(s) based on requirement at the run time, for example which tax strategy to be applied Indian or Chinese. On the other hand, Template pattern puts in some predefined steps (of a algorithm), out of which some are fixed and others can be implemented differently for different usages, say read data from file, parse data, write data to file- parsing might be done differently based on kind of data we are dealing with, but reading from and writing to file will be fixed.

More here –

http://kamalmeet.com/2013/03/understanding-strategy-pattern/
http://kamalmeet.com/2014/04/template-method-design-pattern/
http://stackoverflow.com/questions/669271/what-is-the-difference-between-the-template-method-and-the-strategy-patterns

Template method design pattern

Template method design pattern allows one to create a template of code or algorithm which will provide guidelines for other developers on how to write the solution for different implementations.

To keep it simple, let’s go back to HTML template. HTML template lets you define overall look and feel of page without getting into details. For example, I want all my pages to have a header, a footer, left panel, right panel, middle content panel. I might want to add some parts are fixed, say header and footer will always looks same, but center, right and left can be customized by users.

Same principle is used in template design pattern. Say I have to implement a template reading data from database.

Step 1: get database connection
Step 2: create query
Step 3: Execute Query
Step 4: Parse Data
Step 5: Close connections

Here Step 1, 3 and 5 are common for all type of queries but Step 2 and 4 will be data dependent. This can be achieved by Template Method pattern.

A good explanation can be seen here

templatemethodpatternexample

Image from http://javapostsforlearning.blogspot.in/2013/03/template-method-design-pattern-in-java.html

Composite Design pattern

When I first tried to understand composite design pattern, I came across this UML explanation

composite_pattern

Image source : wikipedia

To start with, I was not able to make any sense out of this, so I tried to look for simpler example, and came up with this

composite2.

Think of a scenario where we need to support a tree format data structure. Where every node can be composed of more similar nodes, or a leaf node. For example in above scenario, at leaf level we have juniors, to whom no one report. At non-leaf level we have managers, to whom, juniors and other managers report, and these managers themselves report to some senior manager. To help us structure this kind of complex relationship, composite design pattern comes into play.

Proxy Design pattern

Proxy design pattern is one of the simplest design pattern. The name explains it all, we place a proxy class between the client and actual implementation. An example is EJB’s home and remote interface implementation. Or think of a webservice call, where we are trying to fetch Employee details from webservice. Instead of calling the webservice directly we bring in a proxy class, which is called by client and it call’s the actual webservice later. The advantage it gives us is that if the webservice call changes, say url for the call changes or pattern of input/ output xml is modifies, we just need to make change at one place, rather than changing calls at multiple clients.

proxy

Bridge Design pattern

When I first tried to understand Bridge pattern, I got it confused with Adapter pattern and then Abstract Factory pattern. In my defense, these patterns do have features overlapping. But when I got into depth of bridge pattern, the advantages got clear i.e. decouple an abstraction from its implementation so that the two can vary independently.

Yes that is very confusing line. A good read to demystify the concept- http://softwarejedi.wordpress.com/2013/04/16/design-patterns-and-scala-the-bridge-pattern/

Adapter design pattern

Adapter design pattern is probably one of the simplest, yet very useful design pattern. Let’s take and example, you have a device which runs on Direct Current (DC), but in your home you have supply of Alternate current (AC). What will you do? Go to an electronic shop and explain the problem, the guy in shop will give you an AC to DC ‘Adapter’. What it does is basically takes AC as input and provide DC as output for your device.

Similar problems are faced at times by developer, especially when they are using API from third party or legacy code. Say you are using a Tax class API (you do not have code) which takes integer to calculate tax in its getTax method, whereas your code stores the data in int. One way is to convert the format at every place in code where ever you are using getTax. A second and simple ‘Adapter’ way will be to create a TaxAdapter class which will have a getTax in it, which further calls getTax of Tax class. The only responsibility of TaxAdapter is to convert the data into a format which is expected by Tax class(double to int, AC to DC).