Pages

Wednesday, March 21, 2012

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.
01public class Song
02{
03  public string GetStyle()
04  {
05      return "Rock n Roll !";
06  }
07}
08 
09public class LineUp
10{
11  public string GetFormation()
12  {
13      return "Trio";
14  }
15}
16 
17public class Singer
18{
19  Song song;
20  LineUp lineUp;
21 
22  public Singer()
23  {
24      song = new Song();
25      lineUp = new LineUp();
26  }
27 
28  public string Sing()
29  {
30      return "Singer sings " + song.GetStyle() + " and it is a " +  lineUp.GetFormation();
31  }
32}
here’s the Main method :
1Singer singer = new Singer();
2Console.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.
01public interface ISong
02{
03  public string GetStyle();
04}
05 
06public interface ILineUp
07{
08  public string GetFormation();
09}
10 
11public class Song : ISong
12{
13  public string ISong.GetStyle()
14  {
15      return "Hip Hop !";
16  }
17}
18 
19public class LineUp : ILineUp
20{
21  public string ILineUp.GetFormation()
22  {
23      return "Solo";
24  }
25}
26 
27public class Singer
28{
29  ISong _isong;
30  ILineUp _ilineup;
31 
32  public string Singer(ISong is, ILineUp il)
33  {
34      _isong = is;
35      _ilineup = il;
36  }
37 
38  public string Sing()
39  {
40      return Singer sings " + _isong.GetStyle() + "it is a " +  _ilineup.GetFormation();
41  }
42}
here’s the Main method : Now if we want to here another artist, we just have to
instanciate so many class that we want
01//Creating dependencies
02Song oldsong = new Song();
03LineUp oldlineUp = new LineUp();
04//Injection of dependencies
05Singer singer = new Singer(oldsong,oldlineup);
06Console.WriteLine(singer.Sing());
07 
08//Creating dependencies
09Song newsong = new Song();
10LineUp newlineUp = new LineUp();
11//Injection of dependencies
12Singer singer = new Singer(newsong,newlineup);
13Console.WriteLine(singer.Sing());
Thanks for reading !!

No comments: