2012-02-09 157 views
2

嗨,我们如何在实时场景中实现接口?接口实现时不透露实现接口的类

这是我的情况

我已经有2种方法

void SaleTransaction(); 
void VoidTransaction(); 

接口IPayPal现在我有一个类的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. 
    } 

} 

即请告诉我的方式。我在初始化我的接口类不透露类实现接口。

感谢

回答

2

我建议:

  1. 阅读有关dependency injection以及如何帮助您轻松解决依赖关系,并在松耦合方式。
  2. 接口名称“IPayPal”不是很好的名字恕我直言。这是一个支付提供商非常具体。假设明天你想实现另一种不是贝宝的支付方式,但你想使用相同的接口。我认为这个名称应该像“IPaymentProvider”一样是通用的,而且当前的实现是PayPal(但是没有其他类使用该接口应该关心或知道这一点)。

祝你好运!

2

两个选项:

  • 不要暴露你不想从其他组件调用,倒也干脆公共方法。不要暴露甚至不希望从程序集中的其他类调用的内部方法。

  • 创建其代理的所有调用的包装:

    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,所以让我们转到那......“破解。

0

您可以将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 
    } 
}