簡體   English   中英

代理設計模式中主類的代碼是什么?

[英]what is the code for main class in proxy design pattern?

請幫助我創建此代理設計模式的主類嗎?

//文件名: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);
    }
}`

//文件名: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{
}

}`

//文件名:PaymentService.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);
}

}

請參閱以下類圖,了解來自以下位置的代理設計模式: http : //www.codeproject.com/Articles/186001/Proxy-Design-Pattern 在此處輸入圖片說明

在您的問題中,您有一個付款接口,即“主題”。 然后,您具有實現了Payment接口的PaymentImpl,這就是“真實主題”。 但是,您在這里缺少“代理”。

您需要編寫一個PaymentProxy類,該類還將實現Payment接口。 此類將引用作為私有字段的“真實主題”(PaymentImpl)類型的對象,並將通過此“真實主題”對象調用從“主題”繼承的方法。

范例:

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


   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM