[英]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
,所以我們將其轉換為那...”駭客。
我會建議:
祝好運!
您可以將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.