IoC Pattern

Introduction:

IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.
As a matter of fact every system does not make assumptions about what other systems do or should do, so no side effect when replacing a system by another one.

Let’s have a first example showing classes having strong dependencies between them. Here we have a main class Singer, which let us know the song style and what formation it is.

public class Song
{
  public string GetStyle()
  {
      return "Rock n Roll !";
  }
}

public class LineUp
{
  public string GetFormation()
  {
      return "Trio";
  }
}

public class Singer
{
  Song song;
  LineUp lineUp;

  public Singer()
  {
      song = new Song();
      lineUp = new LineUp();
  }

  public string Sing()
  {
      return "Singer sings " + song.GetStyle() + " and it is a " +  lineUp.GetFormation();
  }
}

here’s the Main method :

Singer singer = new Singer();
Console.WriteLine(singer.Sing());

As result we have : singer sings Rock n Roll ! and it is a Trio
But what would we do if we want to hear another song?? Hearing the same one is good but at the end it could break your tears!!

Implementation of interfaces to replaces instanciate classes (Song, LineUp), and by this way uncoupling main class Singer with the others.

public interface ISong
{
  public string GetStyle();
}

public interface ILineUp
{
  public string GetFormation();
}

public class Song : ISong
{
  public string ISong.GetStyle()
  {
      return "Hip Hop !";
  }
}

public class LineUp : ILineUp
{
  public string ILineUp.GetFormation()
  {
      return "Solo";
  }
}

public class Singer
{
  ISong _isong;
  ILineUp _ilineup;

  public string Singer(ISong is, ILineUp il)
  {
      _isong = is;
      _ilineup = il;
  }

  public string Sing()
  {
      return Singer sings " + _isong.GetStyle() + "it is a " +  _ilineup.GetFormation();
  }
}

here’s the Main method : Now if we want to here another artist, we just have to
instanciate so many class that we want

//Creating dependencies
Song oldsong = new Song();
LineUp oldlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(oldsong,oldlineup);
Console.WriteLine(singer.Sing());

//Creating dependencies
Song newsong = new Song();
LineUp newlineUp = new LineUp();
//Injection of dependencies
Singer singer = new Singer(newsong,newlineup);
Console.WriteLine(singer.Sing());

Thanks for reading !!

2 thoughts on “IoC Pattern

  1. Thanks, for the info what I got from this site.If possible can you provide Windsor Castle IOC pattern in .Net.

Leave a comment