Category Archives: Design Patterns

SOLID Principles for object oriented design

There are many best practices and principles figured out by developers and architects for object oriented design. Robert Martin has intelligently put a subset of these good practices together, and gave them acronym SOLID which helps easy remembrance.

Single responsibility principle: A class should handle only one single responsibility and have only one reason for change. For example a class “Employee” should not change if there a change in project or some reporting details.

Open Closed principle: Code should be open for extension but closed for modification. If you want to add a new type of report in the system, you should not be changing any existing code. More here

Liskov substitution principle: “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.” So if we have Employee class, which is extended by Manager. We should be able to use Manager instead of Employee and all the Employee methods like calculate Salary, generate annual report etc should work without any issues. Say if there is an object like “ContractWorker” that does not support a few functions of Employee like annual report, one should be careful not to make it subtype of Employee.

Interface Segregation principle: “no client should be forced to depend on methods it does not use”. Coming back to previous example, if “ContractWorker” does not need to support annual report, we should not force it to implement an iEmployee interface. We should break the interfaces say iReport and iEmployee, iEmployee can extent iReport and iContractWorker should implement only iReport. iReport can further be divided into reporting types if required.

Dependency Inversion principle: This one seems to be one of my favorite as I have written about it here, here, here and here. This one indeed is one of the most important design patterns which can be followed to make the code loosely coupled and hence making it more maintainable (golden rule- low coupling + high cohesiveness). In traditional programming, when a high level method calls a low level method, it needs to be aware of the low level method at compile time, whereas using DI we can make high level method depend on an abstraction or interface and details of implementation will be provided at run time, hence giving us freedom to use which implementation to be used. Coming back to my previous example, I can have multiple implementations of Employee Reporting, iReport. Some implementation need and excel report, other might need a PDF reporting, which can be decided at runtime.

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).

JSR 330, more specifically talks about Dependency Injection.

A more elaborated explanation on usage of various DI annotations –

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 –

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()
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()
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()
synchronized(MySingleton.class) {
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.

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 –

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


Image from

Composite Design pattern

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


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


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.


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-