Tag Archives: Design Patterns

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.

Bridge pattern allows an abstraction and implementation to change independently whereas an Adapter pattern makes it possible for incompatible classes to work together

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();
cB.setEngine(e);
//.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();
swift.setMaxSpeed(200);
swift.setMileage(20);
swift.setFuel(Diesel);

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

//more cars

//we will also override clone method if required

public Car getCarFromPrototype(String str)
{
switch(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.

factory

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

AbstractFactory

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.

http://kamalmeet.com/2013/06/factory-pattern/

http://kamalmeet.com/2013/03/understanding-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.