1、第十九章 代理模式,2018/6/12,1,代理模式 为其他对象提供一种代理以控制对这个对象的访问。Proxy Pattern Provide a surrogate or placeholder for another object to control access to it.,一 、 概述,2018/6/12,2,代理模式是为对象提供一个代理,代理可以控制对它所代理的对象的访问。 代理模式最常见的两种情况:远程代理和虚拟代理。,二、代理模式的结构与使用,2018/6/12,3,模式的结构中包括三种角色:抽象主题(Subject) 实际主题(RealSubject) 代理(Proxy),
2、2018/6/12,4,模式的UML类图,2018/6/12,5,模式的结构的描述与使用,1抽象主题(Subject): Geometry.java public interface Geometry public double getArea(); ,2018/6/12,6,模式的结构的描述与使用,2具体模板(Concrete Template): Trangle.java public class Triangle implements Geometry double sideA,sideB,sideC,area; public Triangle(double a,double b,dou
3、ble c) sideA=a; sideB=b; sideC=c; public double getArea() double p=(sideA+sideB+sideC)/2.0; area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC) ; return area; ,2018/6/12,7,模式的结构的描述与使用,3代理(Proxy):TriangleProxy.java public class TriangleProxy implements Geometry double sideA,sideB,sideC; Triangle triangle;
4、 public void setABC(double a,double b,double c) sideA=a; sideB=b; sideC=c; public double getArea() if(sideA+sideBsideC ,2018/6/12,8,模式的结构的描述与使用,4应用 Application.java import java.util.Scanner;public class Application public static void main(String args) Scanner reader=new Scanner(System.in); System.ou
5、t.println(请输入三个数,每输入一个数回车确认); double a=-1,b=-1,c=-1; a=reader.nextDouble(); b=reader.nextDouble(); c=reader.nextDouble(); TriangleProxy proxy=new TriangleProxy(); proxy.setABC(a,b,c); double area=proxy.getArea(); System.out.println(面积是:+area); ,三、代理模式的优点,2018/6/12,9,代理模式可以屏蔽用户真正请求的对象,使用户程序和真正的对象之间解耦
6、。使用代理来担当那些创建耗时的对象的替身。,JavaRMI,CDP Tutorial,Based on,Based on the slides of Alexander Day Chaffee,TCP,Remote Objects (Diagram),Java Virtual Machine,ClientObject,Java Virtual Machine,RemoteObject,What is RMI?,RMI is an RPC system for an object basedlanguage.Objects provide a natural granularity for th
7、ebinding of functions.,RMI allows a program to hold a reference to an objecton a remote system and to call that objects methods.,Client-Server architecture.,Server holds the object.Client holds a small stub that accesses the object onthe Server.,RMI Layers,TCP,Transport Layer,Transport Layer,Java Vi
8、rtual MachineClientObjectStubRemote Reference Layer,Java Virtual MachineRemoteObjectSkeletonRemote Reference Layer,Remote Objects,Remote Objects,Live on serverAccessed as if they were local,Remote References andInterfaces,Remote References,Refer to remote objectsInvoked on client exactly like local
9、objectreferences,Remote Interfaces,Declare exposed methodsImplemented on clientLike a proxy for the remote object,Stubs and Skeletons,Stub,lives on clientpretends to be remote object,Skeleton,lives on serverreceives requests from stubtalks to true remote objectdelivers response to stub,Remote Interf
10、aces and StubsRemote Interface,Stub,Remote Object(Server),Client,Skeleton,implements,implements,Registries,Name and look up remote objectsServers can register their objectsClients can find server objects and obtain aremote referenceA registry is a running process on a hostmachine,RMI System Architec
11、ture,Client Virtual MachineClient,Stub,Server Virtual MachineRemoteObject,Skeleton“Fred”Registry Virtual Machine,Server,1. Server Creates Remote Object,RMI Flow,Stub,Server,Server Virtual MachineRemoteObject1,Skeleton2“Fred”Registry Virtual Machine,Client Virtual Machine2. Server Registers Remote Ob
12、jectClient,3. Client requests object from Registry,4. Registry returns remote reference,RMI Flow,Client Virtual MachineClient,Stub,Server,Skeleton4“Fred”Registry Virtual Machine,Server Virtual MachineRemoteObject(and stub gets created),3,RMI Flow,Stub,Skeleton,Server,6,5. Client invokes stub method6
13、. Stub talks to skeleton7. Skeleton invokes remote objectmethod“Fred”Registry Virtual Machine,Client Virtual MachineClient5,Server Virtual MachineRemoteObject7,RMI Usage,Start registryStart serverRun client,Creating Remote Objects,Define a Remote Interface,extends java.rmi.Remote,Define a class that
14、 implements the RemoteInterface,extends java.rmi.RemoteObjector java.rmi.UnicastRemoteObject,Remote Interface Example,import java.rmi.*;,public interface Adder,extends Remote,public int add(int x, int y),throws RemoteException;,Remote Class Example,import java.rmi.*;,import java.rmi.server.*;,public
15、 class AdderImpl extends UnicastRemoteObject,implements Adder,public AdderImpl() throws RemoteException,/ NOTE: !EMPTY CONSTRUCTOR!,public int add(int x, int y) throws RemoteException,return x + y;,Registering Remote Classes,start the registry,running process,Unix:rmiregistry &Windows:start /m rmire
16、gistry,Registry CLASSPATH,Registry VM needs to be able to find stubfile(s)You must set the CLASSPATH to includethe directory containing the stub fileAn easy way to check CLASSPATH is to use the javap command,supplying a fully package qualified class name. It uses the currentCLASSPATH to find and pri
17、nt the interface to a class.,Create the server,Creates a new instance of the remoteobjectRegisters it in the registry with a uniquenameThats it,RMI Server Example,try ,AdderImpl adder = new AdderImpl();Naming.rebind(adder, adder);,System.err.println(“Bind successful”);,catch (RemoteException re) ,re
18、.printStackTrace();,catch (MalformedURLException me) ,me.printStackTrace();,Launch the Server,% java AdderServerBind successful,Server Logging,invoke from command line,java-Djava.rmi.server.logCalls=trueYourServerImpl,or enable inside program,RemoteServer.setLog(System.err);,Creating an RMI Client,F
19、ind a registry,use java.rmi.Naming,Lookup the name, returns a referenceCast the reference to the appropriateRemote InterfaceJust use it!,RMI URLsrmi:/host:port/name,default port is 1099Specifies hostname of registrycan also use relative URLs,name onlyassumes registry is on local host,RMI Client Exam
20、ple,Adder a = (Adder)/not AdderImpl,Naming.lookup(rmi:/server/adder);,int sum = a.add(2,2);,System.out.println(2+2= + sum);,Remote Interfaces vs. RemoteClasses,Remember that the reference is to aninterfaceYou must make references, arrays, etc. outof the interface type, not theimplementation typeYou
21、cant cast the remote reference to anormal referenceSo name your Remote Objects with “Impl”(so you dont get confused),Parameter Passing,Primitive types,passed by value,Remote objects,passed by reference,Non-remote objects,passed by valueuses Java Object Serialization,Callbacks,They just workPass in a
22、 remote reference to a clientobjectServer object can call its methodstransparentlyRegistry is out of the loop,Object Serialization,aka Persistencesaves the state (data) of a particularinstance of an objectserialize - to saveunserialize - to load,Java Serialization,writes object as a sequence of byte
23、swrites it to a Streamrecreates it on the other endcreates a brand new object with the olddata,java.io.Serializable,Objects that implement thejava.io.Serializable interface are marked asserializableAlso subclassesMagically, all non-static and non-transientdata members will be serializedActually, its
24、 not magic, its Reflection (itsdone with mirrors)empty interface - just a markerIts a promise,Not All Objects AreSerializable,Any object that doesnt implementSerializableAny object that would pose a security risk,e.g. FileInputStream,Any object whose value depends on VM-specific information,e.g. Thr
25、ead,Any object that contains a (non-static, non-transient) unserializable object (recursively),NotSerializableException,thrown if you try to serialize or unserializean unserializable objectmaybe you subclassed a Serializable objectand added some unserializable members,Incompatible Changes,If class h
26、as members added or removed, itbecomes incompatiblejava.io.InvalidClassException thrown if youtry to deserialize an incompatible objectstream,Limitations of RMI,Java-only,but you can use JNI on the server,Uses TCP, not UDPAt least two sockets per connectionUntested for huge loads,Summary,RMI is a ve
27、ry clean APIEasy way to write distributed programsWire protocol may need improvement forlarge-scale problems,Where to get moreinformation,Harold, Java Network Programming(OReilly)rmi-users mailing list (rmi-)http:/ / (Gamelan)http:/ / (magazine)http:/ / java/ (AlexanderDay Chaffees site)Material from the previous semester,