[英]Interface implementation without revealing the class that implements the interface
Hi how do we implement interface in a real time scenario?? 嗨,我们如何在实时场景中实现接口?
This is my situation 这是我的情况
I have made an interface IPayPal which has 2 methods 我做了一个有2种方法的接口IPayPal
void SaleTransaction();
void VoidTransaction();
now i have a class PayPal which implements this service. 现在我有一个实现此服务的PayPal类。
class PayPal:IPayPal{
public void SaleTransaction(){
// Implementation happens here
}
public void VoidTransaction(){
// Implementation happens here
}
}
now i have a service that requests the services from PayPal 现在我有一项服务,要求PayPal提供服务
lets say 可以说
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.
}
}
ie Please tell me a way in which i can initialise my interface class without revealing the class that implements the interface. 即,请告诉我一种可以初始化我的接口类而又不暴露实现该接口的类的方法。
Thanks 谢谢
Two options: 两种选择:
Don't expose public methods you don't want to be called from other assemblies, pretty simply. 简单地说,不要公开不想从其他程序集中调用的公共方法。 Don't expose even internal methods you don't want to be called from other classes in the assembly.
不要公开甚至不想从程序集中其他类调用的内部方法。
Create a wrapper which proxies all calls: 创建一个包装所有代理的包装器:
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(); } }
At this point, you can create a PaymentProxy
with your original "secret" object, trust that not to leak the information about it, and hand the proxy to anything. 此时,您可以使用原始的“秘密”对象创建一个
PaymentProxy
,信任不要泄漏有关其的信息,并将该代理交给任何东西。 Of course, this isn't secure against reflection etc - but it does hide the prevent the implementation details from being "accidentally" used in a quick and dirty, "Well I know it'll really be a PayPal
, so let's just cast to that..." hack. 当然,这对于防止反射等是不安全的-但它确实掩盖了防止实现细节被“偶然地”快速而又肮脏地使用的方法,“好吧,我知道它将真的是
PayPal
,所以我们将其转换为那...”骇客。
I would suggest: 我会建议:
good luck! 祝好运!
You can separate 2 methods into 2 interfaces. 您可以将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.