簡體   English   中英

接口實現,但不公開實現接口的類

[英]Interface implementation without revealing the class that implements the interface

嗨,我們如何在實時場景中實現接口?

這是我的情況

我做了一個有2種方法的接口IPayPal

void SaleTransaction();
void VoidTransaction();

現在我有一個實現此服務的PayPal類。

class PayPal:IPayPal{

    public void SaleTransaction(){
    // Implementation happens here

    }

    public void VoidTransaction(){
    // Implementation happens here

    }



}

現在我有一項服務,要求PayPal提供服務

可以說

class Service{

IPayPal pp=null;


static void Main(){

    pp=new PayPal();
    //Now i do not want to expose all the methods in my class PayPal 
    // is there any other way to just show pp.SaleOneTransaction() method?? i donot want the //PayPal class to be present in this Program..

    //Please tell me how to acheive this.
    }

}

即,請告訴我一種可以初始化我的接口類而又不暴露實現該接口的類的方法。

謝謝

兩種選擇:

  • 簡單地說,不要公開不想從其他程序集中調用的公共方法。 不要公開甚至不想從程序集中其他類調用的內部方法。

  • 創建一個包裝所有代理的包裝器:

     public class PaymentProxy : IPayPal { private readonly IPayPal original; public PaymentProxy(IPayPal original) { this.original = original; } public void SaleTransaction() { original.SaleTransaction(); } public void VoidTransaction() { original.VoidTransaction(); } } 

    此時,您可以使用原始的“秘密”對象創建一個PaymentProxy ,信任不要泄漏有關其的信息,並將該代理交給任何東西。 當然,這對於防止反射等是不安全的-但它確實掩蓋了防止實現細節被“偶然地”快速而又骯臟地使用的方法,“好吧,我知道它將真的是PayPal ,所以我們將其轉換為那...”駭客。

我會建議:

  1. 了解有關依賴項注入及其如何以松散耦合方式輕松幫助您解決依賴項的信息。
  2. 接口名稱“ IPayPal”不是很好的名字恕我直言。 這是非常特定於一個付款提供商。 假設明天您想實現另一種不是paypal的付款方式,但又想使用相同的接口。 我認為該名稱應該像“ IPaymentProvider”一樣通用,並且當前的實現是PayPal(但使用該接口的其他任何類都不應該關心或知道這一點)。

祝好運!

您可以將2種方法分成2個接口。

interface IPayPal1{
    void SaleTransaction();
}
interface IPayPal2{
    void VoidTransaction();
}

class PayPal:IPayPal1, IPayPal2{
    void SaleTransaction(){
        //
    }
    void VoidTransaction(){
        //
    }
}

class Service{
    IPayPal1 pp=null;

    static void Main(){
        pp=new PayPal(); //you cannot access VoidTransaction here
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM