2013-06-29 49 views
0
namespace ScratchPad 
{ 
    public class InterfaceTestBuilder : InterfaceTest1 
    { 
     public InterfaceTestBuilder Init() 
     { 

      return this; 
     } 

     public InterfaceTestBuilder Method1() 
     { 

      return this; 
     } 

     public InterfaceTestBuilder Method2() 
     { 

      return this; 
     } 

     public InterfaceTestBuilder Method3() 
     { 

      return this; 
     } 

    } 

    public interface InterfaceTest1 
    { 
     InterfaceTestBuilder Init(); 
     InterfaceTestBuilder Method3(); 
    } 

    public class Client 
    { 
     public void TestMethod1() 
     { 
      InterfaceTest1 test = new InterfaceTestBuilder(); 

      test.Init(); 
        test.Method3(); 
      test.Init().Method1().Method2().Method3(); 
     } 
    } 
} 

在客戶端類具體的方法,在方法鏈中使用時我的「測試」實例僅限於只是的Init()和方法3()方法,但所有方法都可以訪問。我如何使用接口來限制當我希望我的客戶端使用方法鏈時可訪問的方法?使用的接口,以暴露的方法中的鏈

我還要提到的,有可能是另一個接口,僅公開另一組的具體方法:

public interface InterfaceTest2 
{ 
    InterfaceTestBuilder Init(); 
    InterfaceTestBuilder Method1(); 
} 
+0

你以前見過嗎? AFAIK這是不可能的。您可以返回不同的類型,然後可以從返回類型鏈接在一起,但接口是一個公共(或內部)可見合同 –

+0

我以前沒有見過這種情況,但我已經實現了一個方法鏈接構建器,並希望一個接口將是一個更清潔的實現來揭示基於某些條件/場景的方法。我可以通過將我的InterfaceTestBuilder傳遞給另一個類來使用不同的模式,並通過該類只公開我希望調用者使用的方法。謝謝! – Nventex

回答

0

試着改變方法的返回類型InterfaceTest1

例如,改變你的界面:

public interface InterfaceTest1 
{ 
    InterfaceTest1 Init(); 
    InterfaceTest1 Method3(); 
} 

更改您的InterfaceTestBuilder類實現方法,請執行以下方法:

public InterfaceTest1 Init() 
{ 

    return this; 
} 
public InterfaceTest1 Method3() 
{ 

    return this; 
} 

然後,您將無法進行下面的調用,如調用Method1Init將無法​​訪問:

InterfaceTest1 test = new InterfaceTestBuilder(); 

    test.Init().Method1().Method2().Method3(); 
+0

我忘了提及可能有另一個接口向我的客戶端公開了一組不同的方法。 – Nventex

+2

@Nventex根據這些提及改變你的問題。 – AgentFire