Tag Archives: Design Patterns

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

Builder Pattern

You must have used DocumentBuilder or StringBuilder classes if you have worked with core Java. Buider pattern is simple object creation pattern, which helps handling of creation of complex objects by breaking the object building exercise into multiple easy steps.

A simple example will be- let’s say we have a car object with many complex properties- Engine, top speed, boot_space, seating arrangement, air_conditioning etc. A CarBuilder class can help in creation of the objects

Class CarBuilder{

public void setEngine(Engine e)

public void setSpeed(String s)

public void setAirConditioning(String temp, String cooling, int avgtemp)

public Car getCar()
//This will finally create the car object and return


The calling method

CarBuilder cB=new CarBuilder();
//.so on
Car myCar=cB.getCar();

To make it more useful in handling higher complexity, we can create the CarBuilder as Abstract Class or interface, which is implemented by HatchBackBuilder, SportsCarBuilder etc.

Prototype pattern

Prototype is a creational design pattern. When I first read about it, I got it a bit confused with Factory pattern. If you look at Car Factory example, where the factory helps us create a “new” car at run time, and we can choose whether we want a Sedan or Hatchback while the car creation. Prototype pattern differentiates itself from factory pattern, by providing prototypes of objects beforehand, and creating a copy at runtime.

Extending our Carfactory example further, lets say now we are not limited to 2 set of cars, but we have ready prototypes say a car called Swift, Ritz, Figo, Scorpio, all with their specifications already defined. At runtime, we will just create a copy or clone of the car which user needs. Note that we can actually build our prototype pattern on factory pattern, but for simplicity of this example we will stick to a simple implementation of car by these objects.

public class CarPrototype{

Car swift=new Car();

Car figo=new Car();
//set properties

//more cars

//we will also override clone method if required

public Car getCarFromPrototype(String str)
case ‘FIGO’: return figo.clone();break;
case ‘SWIFT’: retrun swift.clone();break
//so on


One important difference between factory and prototype is that prototype pattern creates a clone and factory pattern create a new object. When a new object is created using a new keyword, it makes sure that user get a object with fresh state. Whereas in clone (prototype), we are making sure that we are also copying a particular state of object. This also helps us understand when to use factory and when prototype should be preferred.

Abtract Factory Pattern

Abstract Factory pattern is another creational design pattern in the league of Factory, Singleton, builder and Prototype patterns. The term has some resemblance to Factory pattern and so does implementation. I tried looking around the internet to figure out some good explanation, but unfortunately they are too complex. This will help though- http://www.oodesign.com/abstract-factory-pattern.html

In my attempt to over simply things, I will try to go back to factory pattern and the example I used for CarFactory, http://kamalmeet.com/2013/06/factory-pattern/. The idea was simple with CarFactory, that user knows he wants a car, but which car is to be created is decided at runtime.


AbstractFactory Extends the idea a bit further, it gives us a factory of factories.


To understand the above diagram, lets extend our CarFactory example, lets say we know that we need a vehicle to start with but we do not know if it will be a car or a bike (decided at runtime). So we will have 2 concrete factories-  CarFactory and BikeFactory. CarFactory is responsible for creating Sedan or HatchBack as previous example and BikeFactory is creating SportsBike and NormalBike. On top of the concrete factories we will introduce a AbstractVehicalFactory which is implemented by CarFactory and BikeFactory.

Factory Pattern vs Strategy Pattern

Factory pattern and Strategy pattern might create a confusion if you are using them for the first time. Atleast I was confused, so I tried to analyze the two patterns further.

Let’s relook at the two examples which we used for factory and strategy pattern.



Car Factory- A factory for creating Sedan or Hatchback car at the run time based on user need.

Tax Calculator- To pick at run time which type of tax to be calculated (Indian or German).

The difference lies in the usage of two examples above. In first example we are creating object of something, so we can conclude factory pattern is a creational pattern. In second example it is clear we are trying to achieve a goal / execute a method based on input, hence strategy pattern is an operational pattern.

Factory Pattern

Factory Pattern is one of the highly used design patterns. The reason being , its genuine usefulness and closeness to real world. Let’s take a very simple real world example to get started, and then we will map it to the pattern.

Let’s say we have a Car factory which creates many types of cars. To keep it simple, let’s say it creates 2 type of cars- hatchback & sedan. These two type of cars will have many similar attributes like top speed, power steering etc. but there will be some features explicit to type of car (say a back seat AC or TV is available only for sedan cars). What will be a natural Object Oriented Design for this arrangement?

Class Car Extended by Class Sedan and Class HatchBack

If you know what type of car you need beforehand, we are good. But in case you need to create the car at runtime, say on user input, you will need some helper class which will create specific type of car at runtime. This class is our factory class.


Class CarFactory


Public static Car getCar(String carType){

If(carType.equals(“sedan”)) return new Sedan();

else return new HatchBack();



A better example in technical terms might be that your application supports multiple database types (say on test environment you use MySql whereas on production you have Oracle). A DataBaseConnectionFactory can help you get connection of specific type of database at runtime (say reading the database type value from some property file.


Singleton Pattern Round Up: All about singleton pattern

Here is summary of what I have written so far on singleton patterns. The examples taken here are mostly from Java.

Singleton Pattern #1: Basics, Definition, Usage
Gives a basic idea of singleton pattern is all about.

Singleton Pattern #2: Lazy vs Eager Instantiation for a Singleton Class
The difference between two types of instantiations, and which one is better under what circumstances.

Singleton Pattern #3: Problems with Singleton, Thread-Safe Singleton Class
Issues with using singleton, how to make your singleton classes threadsafe.

Singleton Pattern #4: Difference between Singleton and Static classes
Sometimes people confuse between singleton and static classes. When should one use them and why?

Singleton Pattern #4: Difference between Singleton and Static classes

The basic differences between singleton and static classes (when we say  static class in java, it is a class with static members) in nutshell are:

1. Singleton classes can hold instance variable while static can’t
2. Singleton classes can be inherited
3. Static classes are more useful while handling the stateless data
4. At a later stage if you think that you need more instances of a singleton class, you can simply modify the class. Basically make the constructor public/ make the singleton class non-singleton, depending on your requirement
5. For simple functionalities where we need utility methods to be implemented on some data and simple return statements, static classes are of better help. For example, creating a string utility or math utility class which have methods like sqare (takes an integer say 2 and return 4 ), cube (takes 2 and simply returns 8 )

Singleton Pattern #3: Problems with Singleton, Thread-Safe Singleton Class

A side effect of using singleton class: as the constructor of the singleton class is private, you cannot create a subclass of a singleton class, but in most of the cases that is desirable. Additionally you can declare the class as final to explicitly show that the class can’t be subclassed. But in case if it is required to create a subclass of singleton class one can define the constructor of singleton class as protective instead of private.

Another point to note is that the singleton classes are not thread-safe. Simply putting it if the two threads enter the

//create new instance.

block simultaneously, it will create two different instances of the class. This is an undesirable condition and cause unwanted behavior in the application. Also note here that in case of eager instantiation this problem does not occur as the instance gets created beforehand.

Making your singleton class thread-safe is easy, you just have to make your getinstance method synchronized.

Public synchronized static singletonExample getInstance()
//if instance is null create else return old instance

Originally posted February 15, 2007

Brought back using archive.org