我真的很喜歡Ninject文檔中解釋事物的方式,所以我只是使用它們的示例。你總是可以在這裏閱讀完整的文檔:https://github.com/ninject/ninject/wiki/_pages
比方說,你有一把劍類是這樣的:
class Sword
{
public void Hit(string target)
{
Console.WriteLine("Chopped {0} clean in half", target);
}
}
的劍也碰到了什麼東西。現在假設你有一個武士班。這個武士階級使用劍攻擊。
class Samurai
{
private Sword _sword;
public Samurai()
{
_sword = new Sword();
}
public void Attack(string target)
{
_sword.Hit(target);
}
}
這一切工作不錯,罰款是這樣的:
class Program
{
public static void Main()
{
Samurai warrior = new Samurai();
warrior.Attack("the evildoers");
}
}
你現在有被緊密耦合劍類武士階層。什麼時候你想擁有武士軍隊?有的使用劍,有的使用弓箭,有的使用Shuriken。每次添加新武器時,您都必須修改您的武士課程。因爲那就是劍,弓箭和手裏劍。他們都是武士可以使用的所有武器,擊中的東西。
這是接口的作用。讓我們抽象出的使用的接口武器攻擊功能:
interface IWeapon
{
void Hit(string target);
}
class Sword : IWeapon
{
public void Hit(string target)
{
Console.WriteLine("Chopped {0} clean in half", target);
}
}
class BowAndArrow : IWeapon
{
public void Hit(string target)
{
Console.WriteLine("Shot {0} right in the chest!", target);
}
}
class Shuriken : IWeapon
{
public void Hit(string target)
{
Console.WriteLine("Pierced {0}'s armor", target);
}
}
我們現在已經是一個接口IWeapon和三個類實現該接口。界面就像合同一樣。它說:「如果你實現了我,你必須提供Hit方法,該方法應該接受一個字符串參數,並且不應該返回任何東西」。
對於我們的武士有什麼變化?它現在可以使用如下的接口IWeapon:
class Samurai
{
private IWeapon _weapon;
public Samurai(IWeapon weapon)
{
_weapon = weapon;
}
public void Attack(string target)
{
_weapon.Hit(target);
}
}
現在,武士職業使用IWeapon。因爲實現IWeapon接口的每個類同意提供Hit方法的合同,所以Samurai類不需要知道或關心它正在使用的武器。它只知道它有一個武器,它可以擊中is。
像這樣:
class Program
{
public static void Main()
{
Samurai warrior1 = new Samurai(new Sword());
Samurai warrior2 = new Samurai(new Shuriken());
Samurai warrior3 = new Samurai(new BowAndArrow());
warrior1.Attack("the evildoers");
warrior2.Attack("the big guy in front");
warrior3.Attack("the scared guy running away");
}
}
我希望這有一定的道理。
+1:沒有以相同的方式處理公共基類的不同類型似乎是m e – Patrick 2010-12-06 09:46:55