2014-12-05 44 views
0

請幫我創建此代理設計模式的主類?代理設計模式中主類的代碼是什麼?

//Filename:Payment.java

import java.math.*; import java.rmi.*; 
    public interface Payment extends Remote{ 
    public void purchase(PaymentVO payInfo, BigDecimal price) 
     throws PaymentException, RemoteException; } 

//文件名:PaymentException.java

`public class PaymentException extends Exception{ 
    public PaymentException(String m){ 
     super(m); 
    } 
    public PaymentException(String m, Throwable c){ 
     super(m, c); 
    } 
}` 

//Filename:PaymentImpl.java

`import java.math.*; 
    import java.net.*; 
    import java.rmi.*; 
    import java.rmi.server.*; 
      public class PaymentImpl implements Payment{ 
      private static final String PAYMENT_SERVICE_NAME = "paymentService"; 

     public PaymentImpl() throws RemoteException, MalformedURLException{ 
    UnicastRemoteObject.exportObject(this); 
    Naming.rebind(PAYMENT_SERVICE_NAME, this); 
} 
public void purchase(PaymentVO payInfo, BigDecimal price) 
    throws PaymentException{ 
} 

}`

//文件名:Paym entService.java

import java.math.*; 
public interface PaymentService{ 
    public void purchase(PaymentVO payInfo, BigDecimal price) 
     throws PaymentException, ServiceUnavailableException; 
} 

//文件名:PaymentVO.java

public class PaymentVO{ 
} 

//文件名:ServiceUnavailableException.java

public class ServiceUnavailableException extends Exception{ 
public ServiceUnavailableException(String m){ 
    super(m); 
} 
public ServiceUnavailableException(String m, Throwable c){ 
    super(m, c); 
} 

}

+0

你似乎在這裏失去了幾節課。你可以檢查一下嗎? – maheeka 2014-12-05 05:46:58

回答

0

,給予代理的類圖下面設計模式來自:http://www.codeproject.com/Articles/186001/Proxy-Design-Patternenter image description here

在你的問題中,你有一個支付界面,這是「主題」。然後你有PaymentImpl實現支付接口,這是「真正的主題」。但是,您在這裏錯過了「代理」。

您需要編寫一個PaymentProxy類,該類還將實現支付接口。這個類將引用「Real Subject」(PaymentImpl)類型的對象作爲私有字段,並將通過此「Real Subject」對象調用從「Subject」繼承的方法。

例子:

public class PaymentProxy implements Payment{ 

    private PaymentImpl realPayment; 

    public PaymentProxy(){ 

    } 

    public void purchase(PaymentVO payInfo, BigDecimal price) throws PaymentException{ 
     if(realPayment==null){ 
      realPayment = new PaymentImpl(); 
     } 
     realPayment.purchase(payInfo, price); 
    } 
} 

您可能會注意到realPayment是按需使用代理設計模式時創建的。當對象創建昂貴時,這非常有用。

以下是主類代碼:

public class Client{ 
    public static void main(String[] args){ 

     PaymentProxy paymentProxy = new PaymentProxy(); //note that the real proxy object is not yet created 
     //... code for resolving payInfo and price as per the requirement 
     paymentProxy.purchase(payInfo, price); //this is where the real payment object of type PaymentImpl is created and invoked 


    } 

}

+0

你從哪裏得到BigDecimal?我能問問主要課程是什麼? – 2014-12-05 06:13:59

+0

大十進制是您在購買方法中的問題。在主要方法中,您需要創建PaymentProxy的實例並使用。這將在上圖中由「客戶」引用的單獨課程中。根據您的問題中的新編輯, – maheeka 2014-12-05 06:20:08

+0

添加了主要方法。 :) – maheeka 2014-12-05 07:57:31