- 定义:为另外一个对象提供一个替身或占位符以控制对这个对象得访问。
- 远程代理:可以作为另外一个JVM上对象得本地代表,调用代理得方法,会被代理利用网络转发到远程执行,并且结果会通过网络返回给代理,再由代理将结果转给客户。利用java得RMI技术实现
//服务接口类
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
//服务实现类
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
private static Logger logger = LoggerFactory.getLogger(MyRemote.class);
protected MyRemoteImpl() throws RemoteException {
}
@Override
public String sayHello() throws RemoteException {
return "Server says, hey";
}
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.createRegistry(1099);
MyRemote myRemote = new MyRemoteImpl();
registry.rebind("RemoteHello", myRemote);
System.out.println("start");
} catch (Exception e) {
logger.info("MyRemoteImpl is fail", e);
}
}
}
//客户端
public class MyRemoteClient {
public static void main(String[] args) {
new MyRemoteClient().go();
}
public void go() {
try {
//Naming.lookup("rmi://192.168.1.61:1099/user");
MyRemote myRemote = (MyRemote) Naming.lookup("rmi://192.168.1.102:1099/RemoteHello");
String s = myRemote.sayHello();
System.out.println(s);
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
- 虚拟代理:虚拟代理作为创建开销打得对象得代表。虚拟代理经常直到我们真正需要一个对象得时候才创建。当对象在创建前和创建中时,又虚拟代理来扮演对象得替身。对象创建后,代理就会将请求直接委托给对象。