接口实现,而不透露实现该接口的类

本文关键字:接口 实现 透露 | 更新日期: 2023-09-27 18:23:47

嗨,我们如何在实时场景中实现接口??

这是我的情况

我已经做了一个接口IPayPal,它有两种方法

void SaleTransaction();
void VoidTransaction();

现在我有一个类PayPal,它实现了这项服务。

class PayPal:IPayPal{
    public void SaleTransaction(){
    // Implementation happens here
    }
    public void VoidTransaction(){
    // Implementation happens here
    }

}

现在我有一个服务,要求从贝宝服务

比方说

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.
    }
}

即,请告诉我一种方法,我可以在不透露实现接口的类的情况下初始化接口类。

感谢

接口实现,而不透露实现该接口的类

我建议:

  1. 阅读依赖项注入,以及它如何帮助您以松散耦合的方式轻松解决依赖项
  2. 接口名称"IPayPal"不是很好的名称IMHO。它非常针对一个支付提供商。假设明天你想实现另一种不是贝宝的支付方式,但你想使用相同的接口。我认为名称应该像"IPaymentProvider"一样通用,并且当前的实现是PayPal(但使用该接口的其他类不应该关心或知道这一点)

祝你好运!

两个选项:

  • 不要公开不希望从其他程序集调用的公共方法,非常简单。即使是不希望从程序集中的其他类调用的内部方法,也不要公开。

  • 创建一个代理所有调用的包装器:

    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();
        }
    }
    

    此时,您可以使用原始的"secret"对象创建一个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
    }
}