代理模式
一、代理模式概念
代理模式:当实际对象由于某些原因不能够直接访问,就让代表对象控制对它的访问。
远程代理调用流程:客户端有一个称为桩的辅助对象,服务端有一个称为骨架的辅助对象,客户端不知道要调用的对象在远方,调用辅助对象就像调用实际对象一样。实际上,客户端发送调用申请给桩,桩与骨架通信,骨架请求调用实际方法,将返回值以序列化的对象返回到客户端。
二、代码
MyRemote.java
import java.rmi.Remote; import java.rmi.RemoteException; public interface MyRemote extends Remote{ public String sayHello(String name) throws RemoteException; }
MyRemoteImpl.java
import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{ MyRemoteImpl() throws RemoteException {} public String sayHello(String name) { return name + " hello!"; } }
RegistService.java
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class RegistService { public static void main(String[] args) { try { Registry registry = LocateRegistry.createRegistry(1099); MyRemoteImpl m = new MyRemoteImpl(); registry.bind("hello", m); System.out.println("regist success"); }catch(Exception e) { } } }
MyClient.java
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class MyClient { public static void main(String[] args) { try { Registry registry = LocateRegistry.getRegistry(1099); MyRemote my = (MyRemote)registry.lookup("hello"); System.out.println(my.sayHello("Mike")); }catch(Exception e) {} } }
代理这部分有点复杂,笔者现在只是了解一点点,以后再来深入学习趴。