Category Archives: Design Patterns

Program to an interface, not an implementation.

In Software Development process more time is spent on maintaining the code rather than its development and during this period there may be requirement of new classes. By Programing to Interfaces your application/code is always open for modification without much code change.

Like if you coded to concrete classes then your code will look something like this

public ProcessedTea processTea(Tea tea){  
ProcessedTea processedTea = tea.getProcessedTea();  
return processedTea;  

But if you program to Interfaces then it can be made generic


public ProcessedFood processFood(FoodItem foodItem){  
ProcessedFood processedFood = foodItem.getProcessedFood();  
return processedFood;  

UML Diagram:

Here FoodItem is an Interface and rest of the classes like Tea, Coffee etc implements it.

Now if there is any new addition of any foodItem/Beverages then its a lot easier for you to process it as the method processFood(FoodItem foodItem) takes an implementation of FoodItem. On the other hand if you have programmed to concrete classes like the code given at first then you have to write new method for every food type.

Hope it makes clear that why programming to interfaces is more useful as compared to program to concrete classes.

1 Comment

Posted by on April 7, 2010 in Design Patterns, Java


Tags: ,

Strategy Pattern

Strategy pattern defines a family of algorithm which can be used to give desired behaviors to the Objects dynamically.
Objects which can have different behaviors in their life time are harder to manage and it is difficult to use only inheritance to solve the purpose of code-reuse.  So here composition seems to be a better candidate which can ease this situation.

Implementing Strategy Pattern and following the practice of Programming to Interfaces make things flexible enough. Behaviors can be added or changed at runtime. Algorithms/Behaviors can be added to its Family at any time and so does adding behavior to the Object is as easy as calling a setter and passing the new Behaviors Object reference.

To demonstrate this lets consider the following figure.

Here in this figure Vehicle class can have the functionality of start by any means like StartByKick or StartByBattery. These behaviors can be added to any class/subclass of Vehicle. Programming to Interfaces gives the flexibility of even extending and using the family of StartBehaviors.

The most apparent drawback of this Design Pattern is that the Behavior Classes which can be termed as Family Of Algorithms are not in adherence of OOPS. They do not represent a fully qualified Object with its properties and methods. Here the Object/Class is only to have  some specific implementation of Algorithm.

Leave a comment

Posted by on April 1, 2010 in Design Patterns