- 代理模式
代理模式会给某个对象提供一个代理对象,并且有代理对象控制原对象的引用。通俗的说,就是给实际对象找个代理人,由他负责对外的的联系,例如现实社会中的代理律师。由于代理模式相对较多,这里会提出几个使用比较多的代理模式作为示例。 - 代理模式的实例
2.1. 远程代理模式(RMI)
远程代理实际上就是,为一个位于不同的地址空间的对象提供一个本地代理对象。这个不同的地址空间可以是在同一台主机中,也可能是在另一台主机中,远程代理又叫做大使。
2.1.1. JAVA的RMI实现远程代理的方法
服务端
- 制作远程接口
该接口需要实现java.rmi.Remote
类,从而标记该接口的方法可能会被非本地调用。
远程接口中的所有方法都需要声明java.rmi.RemoteException
异常,用于处理网络通信中可能产生的异常。
远程接口方法或者变量的返回值都是可序列化的类型,这是由于存在返回值或者变量需要远程传输的情况。 - 远程接口的实现
继承java.rmi.server.UnicastRemoteObject
类,该类提供远程对象 - 启动本地RMI registry
可以使用JDK自带的rmiregistry命令启动,也可以使用java.rmi.registry.LocateRegistry
提供的createRegistry
方法启动 - 注册远程服务
使用JNDI注册服务
客户端 - 只需要使用JNDI服务找到远程对象,使用即可。
2.1.2. 远程代理模式实例代码
服务端相关代码:
public interface Caculate extends Remote {
int add(int a,int b) throws RemoteException;
int sub(int a,int b) throws RemoteException;
int mul(int a,int b) throws RemoteException;
int div(int a,int b) throws RemoteException;
}
public class CaculateImpl extends UnicastRemoteObject implements Caculate {
protected CaculateImpl() throws RemoteException {
}
@Override
public int add(int a, int b) throws RemoteException {
return a+b;
}
@Override
public int sub(int a, int b) throws RemoteException {
return a-b;
}
@Override
public int mul(int a, int b) throws RemoteException {
return a*b;
}
@Override
public int div(int a, int b) throws RemoteException {
return a/b;
}
}
public class ServiceMain {
public static void main(
String[] args) {
try {
// 创建远程服务对象
Caculate caculate = new CaculateImpl();
// 绑定远程服务对象到 rmiregistry
LocateRegistry.createRegistry(8088);
Naming.rebind("rmi://127.0.0.1:8088/CalculatorService", caculate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端相关代码
public class Client {
public static void main(String[] args) {
try {
Caculate caculate = (Caculate)
Naming.lookup( "rmi://127.0.0.1:8088/CalculatorService");
int result = 0;
result = caculate.add(1,2);
System.out.println("add------"+result);
result = caculate.div(5,1);
System.out.println("div------"+result);
result = caculate.mul(3,3);
System.out.println("mul------"+result);
result = caculate.sub(8,4);
System.out.println("sub------"+result);
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}