Tuesday, February 13, 2018

Chain of responsibility design pattern


In this behavioral design pattern, request is handled using a chain of objects. This is used to eliminate series of if...else if...else if... statements. Thus, each of the processing object contains only the related logic (as in an if statement). It is also possible to execute all the processing objects.
Since the chain work independently new handlers can be added easily, and also existing handlers can be removed.

Image source wikipedia

Let's see a sample.

Monday, February 12, 2018

IoC, DI and Spring


"program to interface not implementation"

IoC and DI

Both words are used interchangeably in Java world but there is a difference.
Inversion of Control is a more general concept
Dependency Injection is a concrete pattern

IoC - Inversion of Control

Inverts responsibility of managing object life cycle (create, initialize, destroy, etc). In simple term, let someone else to create objects for you instead of using "new" in code itself. Normally this someone else is Ioc Container.

IoC Container

Framework to create dependencies and inject them automatically when required.

DI - Dependency Injection

Objects are depending on other Objects. In DI, Objects are given (injects) their dependencies (other objects) through their constructors, methods, fields.

IoC with DI

So if DI means objects are injected who is doing that. Here is where IoC comes in to play. With IoC dependencies are managed by the container.

Spring Framework

Spring Framework is the most famous Inversion of control container for Java applications.
The Spring IoC container is responsible for managing life cycles of specific objects. Creating these objects, calling their initialization methods and configuring these objects by wiring them together.
These objects are typically called as beans.
BeanFactory container - simplest container providing basic support for DI.
ApplicationContext container - adds more enterprise specific functionalities.


  • Reduce coupling
  • Improve testability
  • Flexibility

Further reading