![](/img/trans.png)
[英]What is the ISubject and Operation() of the code in proxy design pattern?
[英]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.