2012-02-09 95 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 
    } 
}