Design ModeProxy mode: provides a replacement or placeholder for another object to control access to this object. The proxy mode is used to create representative objects so that representative objects can control access to an object. The objects to be proxies can allow remote objects (Remote proxies) and create overhead objects (Virtual proxies ), or an object that requires security control (protection proxy ).
Remote Proxy: it can be used as a local representative of an object on another JVM. The method that calls the proxy will be forwarded to remote execution by the proxy, and the result will be returned to the proxy through the network, and then the proxy will return the result to the customer. Virtual Proxy: represents an object with high overhead. A virtual proxy is often created until we actually need an object. When an object is created and before it is created, the virtual proxy acts as the proxy of the object. After an object is created, the proxy directly delegates the request to the object. Dynamic Proxy: java in java. lang. the reflect package has its own Proxy Support. With this package, you can dynamically create a proxy class at runtime to implement one or more interfaces, and forward the call of the method to the class you specified. The actual proxy class is created at runtime. in Java, we call this technology a dynamic proxy. Java Dynamic proxy can be used to implement proxy protection. Firewall Proxy: controls access to network resources and protects the subject from "bad customers. Intelligent reference Proxy: When a topic is referenced, perform additional actions, such as calculating the number of times an object is referenced. Cache Proxy: provides temporary storage for overhead computing results. It also runs multiple clients to share the results to reduce computing or network latency. Synchronous Proxy: Provides secure access to topics in the case of multiple threads. Complex hidden Proxy: used to hide the complexity of a complex set of classes and perform access control. Sometimes it becomes the appearance proxy. The complex hidden proxy and appearance mode are different because the proxy controls access, while the appearance mode only provides another set of interfaces. Copy proxy during write: used to control object replication. The method is to delay object replication until the customer really needs it. This is a variant of the virtual proxy.
Remote service creation(1) remote interface creation (2) Remote implementation (3) Use rmic to generate stub and skeleton (4) Start RMI registry (5) to start remote service
Design principlesMultiple combinations of encapsulation changes, less inheritance for interface programming, less effort class for implementing programming for sending Coupling Design Between interaction objects, should be extended for development, dependency abstraction should be disabled for modification, instead of relying on a specific class, I only talk to my friends and don't look for me. I will look for your class for only one reason to change.
Key PointsThe proxy is similar to the decorator in structure, but has different purposes. The modifier mode adds behavior to the object, while the proxy controls behavior. Like other wrapper, proxy will increase the number of classes in your design.
Remote proxy
Import java. rmi. remote; // naming class used for rmiregistry lookup in java. import java. rmi. remoteException; // extends Remote indicates that this interface is used to support Remote calls of public interface GumballMachineRemote extends Remote {// prepare the supported methods, remoteException should be thrown for each remote method call. // each remote method call must be considered as "risky" public int getCount () throws RemoteException; public String getLocation () throws RemoteException; // The return value is sent back to the customer from the server over the network. Therefore, it must be a primitive or serializable public State getState () throws Re. MoteException;} // extend the Serializable interface so that the State can serialize public interface State extends Serializable {public void insertQuarter (); public void ejectQuarter (); public void turnCrank (); public void dispense ();} public class HasQuarterState implements State {private static final long serialVersionUID = 768887299984514010L; Random randomWinner = new Random (System. currentTimeMillis (); // for each city and county of the State, we are in the GumballMachine instance. In this example, the transient keyword is added before the variable, so that the JVM does not serialize this field transient GumballMachine gumballMachine; // other methods} // GumballMachine to inherit UnicastRemoteObject to become a remote service // GumballMachine also needs to implement the GumballMachineRemote remote interface public class GumballMachine extends UnicastRemoteObject extends {/***/private static final long serialVersionUID =-2838970117227273571L; state soldOutState; State noQuarterState; State hasQuarter State; State soldState; State winnerState; State state = soldOutState; int count = 0; String location; // The constructor must throw a RemoteException, this is because the superclass is the public GumballMachine (String location, int numbergumbils) throws RemoteException {soldOutState = new SoldOutState (this); noQuarterState = new NoQuarterState (this ); hasQuarterState = new HasQuarterState (this); soldState = new SoldState (this); winnerState = new WinnerState (t His); this. count = numbergumbils; if (numbergumbils> 0) state = noQuarterState; this. location = location;} public void insertQuarter () {state. insertQuarter ();} public void ejectQuarter () {state. ejectQuarter ();} public void turnCrank () {state. turnCrank (); state. dispense ();} void setState (State state) {this. state = state;} void releaseBall () {System. out. println ("A gumball comes rolling out the slot... "); if (Count! = 0) {count = count-1 ;}} public void refill (int count) {this. count = count; state = noQuarterState;} public int getCount () {return count;} public State getState () {return state;} public String getLocation () {return location ;} // other methods} // register public class GumballMachineTestDrive {public static void main (String [] args) {GumballMachineRemote gumballMachine = null; int count; if (args. length <2) {System. out. println ("GumballMachine
"); System. exit (1);} try {// you need to add try/catch before instantiating the code, because our constructor may throw an exception count = Integer. parseInt (args [1]); gumballMachine = new GumballMachine (args [0], count); // We also add the Naming. call the rebind and use the gumballmachine name to publish the stubNaming of the GumballMachine. rebind ("//" + args [0] + "/gumballmachine", gumballMachine);} catch (Exception e) {e. printStackTrace () ;}}// the GumballMonitor client public class GumballMonitor {// depends on this GumballMachineRemote remote interface, instead of the specific class GumballMachineRemote machine; public GumballMonitor (volume machine) {this. machine = machine;} public void report () {// when our view calls methods that ultimately occur over the network, do I need to capture all possible remote exceptions? try {System. out. println ("Gumball Machine:" + machine. getLocation (); System. out. println ("Current inventory:" + machine. getCount () + "gumbils"); System. out. println ("Current state:" + machine. getState ();} catch (RemoteException e) {e. printStackTrace () ;}}// monitoring test program public class GumballMonitorTestDrive {public static void main (String [] args) {String [] location = {"rmi: // configure "," rmi: // configure "," rmi: // seattle.mightygumball.com/gumballmachine "}; GumballMonitor [] monitor = new GumballMonitor [location. length]; for (int I = 0; I <location. length; I ++) {try {// create a proxy for each remote machine. The customer searches for the Proxy from Register, that is, the stub object GumballMachineRemote machine = (GumballMachineRemote) Naming. lookup (location [I]); monitor [I] = new GumballMonitor (machine); System. out. println (monitor [I]);} catch (Exception e) {e. printStackTrace () ;}/// print the report for (int I = 0; I <monitor. length; I ++) {monitor [I]. report ();}}}
Virtual proxy
Class ImageProxy implements Icon {ImageIcon imageIcon; URL imageURL; Thread retrievalThread; boolean retrieving = false; // we pass the image url to the constructor, this is the location of the image we want to display. public ImageProxy (URL url) {imageURL = url;} public int getIconWidth () {if (imageIcon! = Null) {return imageIcon. getIconWidth () ;}else {// return the default width and height: return 800; }} public int getIconHeight () {if (imageIcon! = Null) {return imageIcon. getIconHeight () ;}else {return 600 ;}} public void paintIcon (final Component c, Graphics g, int x, int y) {if (imageIcon! = Null) {// If an icon already exists, tell it to draw its own imageIcon. paintIcon (c, g, x, y);} else {g. drawString ("Loading CD cover, please wait... ", x + 300, y + 190); if (! Retrieving) {// if we haven't tried to retrieve the Image retrieving = true; // we don't want the entire user interface to be suspended, so we use another Thread to retrieve the image retrievalThread = new Thread (new Runnable () {public void run () {try {// In this Thread we instantiate the icon object, the constructor returns imageIcon = new ImageIcon (imageURL, "CD Cover") after the image is loaded. // After the image is ready, the constructor tells Swing to re-paint c. repaint ();} catch (Exception e) {e. printStackTrace () ;}}); retrievalThread. start () ;}}} public class ImageProxyTestDrive {ImageComponent imageComponent; JFrame frame = new JFrame ("CD Cover Viewer"); JMenuBar menuBar; JMenu menu; Hashtable
Cds = new Hashtable
(); Public static void main (String [] args) throws Exception {ImageProxyTestDrive testDrive = new ImageProxyTestDrive ();} public ImageProxyTestDrive () throws Exception {// create a framework and menu // create an image proxy and specify the initial URLIcon icon = new ImageProxy (initialURL ); // wrap the proxy into the component imageComponent = new ImageComponent (icon); frame. getContentPane (). add (imageComponent); frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); frame. setSize (800,600); frame. setVisible (true);} URL getCDUrl (String name) {try {return new URL (String) cds. get (name);} catch (MalformedURLException e) {e. printStackTrace (); return null ;}}}