请帮我创建这个代理设计模式的主要类?
//文件名: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);
}
}
答案 0 :(得分:0)
请参阅下面的代理设计模式的类图:http://www.codeproject.com/Articles/186001/Proxy-Design-Pattern
在您的问题中,您有一个付款界面,即“主题”。然后你有PaymentImpl,它实现了Payment接口,这就是“Real Subject”。但是你在这里缺少“代理”。
您需要编写一个PaymentProxy类,它也将实现Payment接口。此类将引用“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
}
}