Interface和abstract class
OOP必談面向“介面”編程,此介面並非僅指“Interface”,它包括“介面”和“抽象類別”。
OOP中的原則很多,什麼SRP,OCP,DIP,ISP,LSP。
而“介面”和“抽象類別”又與DIP(依賴倒置原則)密切相關。DIP強調的是依賴抽象不依賴實際,這樣可以降低系統的耦合性。舉個簡單的例子:
Man man = new Man();
man.Talk();
這樣耦合性很高,如果改為Women兩行代碼都需要修改,所以演化為(Human為抽象類別,依賴抽象):
Human human= new Man();
human.Talk();
如果該為Women的話就修改new Man()為new Women()即可。當然這樣還是有耦合性,解決方案可以參考我設計模式文章中關於工廠的介紹,這裡先寫個代碼供大家思考:
Human human = humanFactory.CreateHuman("xxxx");//簡單工廠
human.Talk();
然而介面和抽象類別的區別是什麼那?
1)介面沒有任何實現,抽象類別可以包含實現。
2)介面支援多繼承,抽象類別不支援多繼承。
3)繼承介面的類實現介面成員時不需要其他關鍵字,繼承抽象類別的類實現抽象類別成員時需要用到override或者new。
4)介面繼承分為顯示繼承和隱式繼承。隱式繼承需要存取修飾詞,顯示不需要存取修飾詞,直接用[介面名].[函數名]。
另:
override只能重寫標記為virtual,abstract,override的成員。
顯示實現的介面函數需要用介面對象調用,不能用實現介面的類的對象調用;隱式實現的介面均可調用。
new標記的成員當用父類對象調用時調用的是父類的方法,override標記的成員當用父類對象調用時調用的是子類的方法。
一下是代碼:using System;
class Stater
{
static void Main()
{
//抽象類別
AbstractClass abstractClass = new TestTwo();
abstractClass.Init();
abstractClass.Show();
abstractClass.ShowTwo();//new覆蓋,調用父類方法
abstractClass.ShowThree();//override重寫,調用子類方法
TestTwo ttObj = new TestTwo();
ttObj.Init();
ttObj.Show();
ttObj.ShowTwo();//new覆蓋,調用子類方法
ttObj.ShowThree();//override重寫調用子類方法
//介面
IInterface iinterface = new Test();
iinterface.Init();
iinterface.Show();
Test test = new Test();
//test.Init();//Error:顯示聲明只能介面調用
test.Show();
}
}
abstract class AbstractClass
{
public void Init()
{
Console.WriteLine("AbstractClass Init.");
}
public abstract void Show();
public virtual void ShowTwo()
{
Console.WriteLine("AbstractClass ShowTwo.");
}
public virtual void ShowThree()
{
Console.WriteLine("AbstractClass ShowThree.");
}
}
interface IInterface
{
string Property { get;}
void Init();
void Show();
}
class Test : IInterface
{
public string Property
{
get
{
return "Property";
}
}
void IInterface.Init()
{
Console.WriteLine("Interface Init.[顯示]");
}
public void Show()
{
Console.WriteLine("Interface Show.[隱式]");
}
}
class TestTwo : AbstractClass
{
public override void Show()
{
Console.WriteLine("TestTwo show.");
}
public new void ShowTwo()
{
Console.WriteLine("TestTwo showtwo.");
}
public override void ShowThree()
{
Console.WriteLine("TestTwo showthree.");
}
}