c# interface 的理解(原廠模式)簡單一實例

來源:互聯網
上載者:User

由於昨天在一個大公司面試,被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有了最基本的認識,也是剛剛理解這些東西,所以肯定有一些漏洞,但是我會繼續加油,努力把這部分學好的。

加油!

 

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/alonesword/archive/2006/12/13/1441012.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.