C# interface實例淺析
下面我們向你介紹一個簡單C# interface的實例,但是首先我們要先明白什么是C# Interface以及什么是工廠模式,那么我們將會結合實例向你介紹這兩個概念。
C# interface定義:就是以前使用的類似于API 的東西,別人告訴你一個類型,你在心得開發過程中可以使用。
比如:
- interface ITest
- {
- string iText();
- }
- class Test:ITest
- {
- #region ITest Members
- public string iText()
- {
- // TODO:Add Test.printText implementation
- return ("Test string.");
- }
- #endregion
- }
- class Test2:ITest
- {
- #region ITest Members
- public string iText()
- {
- // TODO:Add Test.printText implementation
- return ("Test2 string.");
- }
- #endregion
- }
- class Factory
- {
- public static ITest create(int itype)
- {
- if(itype==1)
- {
- return new Test();
- }
- else
- {
- return new Test2();
- }
- }
- }
- private void button1_Click(object sender,
- System.EventArgs e)
- {
- ITest it=Factory.create(2);
- this.label1.Text=it.iText();
- }
- }
Test 和 Test2 都是繼承接口 ITest ,在使用ITest時候,使用了簡單的Factory模式來建立,本來是使用了Rose來畫一個UML模型上來也許講解的更詳細,但是Rose也是這次學習的一點,所以沒有使用會,正在研究中.
1、接口Interface : 并不是我想象的那么可怕,如果我簡單的理解就是一個戶口登記的地方,在這里登記的用戶(方法),在他的兒子(實現接口的類型: Test ,Test2)中,就必須承認Interface中的人員的存在,并且必須給安排一個位置(實現接口的內容)。所以接口的最簡單的好處就是:保持了繼承型,使更多的人聯系起來。
2、工廠模式:Facory Model:最開始接觸這些東西是在Patterns In Java 的PDF中看到的,因為模式的編程方式是對接口編程的,所以開始理解這些方面的時候理解上有問題了。現在總算能明白一點點了。工廠模式就是(ITest)的新生兒(接口的實現類: Test,Test2)的戶口登記處,到時候不管你要用那個兒子,只需要在這注冊一下,就OK了。
簡單的一個實例,讓我對接口interface和Factory Model有了最基本的認識。
C# interface的實例的淺析就向你介紹到這里,希望對你了解和學習C# interface有所幫助。
【編輯推薦】