zoukankan      html  css  js  c++  java
  • HeadFirst设计模式之代理模式

    一、

    1.The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

    Your client object acts like it’s making remote method calls.But what it’s really doing is calling methods on a heap-local ‘proxy’ object that handles all the low-level details of network communication.

    2.

    3.

    4.

    5.

    6.

    二、只能在本地监控的

    1.

      1 package headfirst.designpatterns.proxy.gumballmonitor;
      2 
      3 public class GumballMachine {
      4     State soldOutState;
      5     State noQuarterState;
      6     State hasQuarterState;
      7     State soldState;
      8     State winnerState;
      9  
     10     State state = soldOutState;
     11     int count = 0;
     12      String location;
     13  
     14     public GumballMachine(String location, int count) {
     15         soldOutState = new SoldOutState(this);
     16         noQuarterState = new NoQuarterState(this);
     17         hasQuarterState = new HasQuarterState(this);
     18         soldState = new SoldState(this);
     19         winnerState = new WinnerState(this);
     20 
     21         this.count = count;
     22          if (count > 0) {
     23             state = noQuarterState;
     24         } 
     25         this.location = location;
     26     }
     27  
     28     public void insertQuarter() {
     29         state.insertQuarter();
     30     }
     31  
     32     public void ejectQuarter() {
     33         state.ejectQuarter();
     34     }
     35  
     36     public void turnCrank() {
     37         state.turnCrank();
     38         state.dispense();
     39     }
     40 
     41     void setState(State state) {
     42         this.state = state;
     43     }
     44  
     45     void releaseBall() {
     46         System.out.println("A gumball comes rolling out the slot...");
     47         if (count != 0) {
     48             count = count - 1;
     49         }
     50     }
     51  
     52     public int getCount() {
     53         return count;
     54     }
     55 
     56     public void refill(int count) {
     57         this.count = count;
     58         state = noQuarterState;
     59     }
     60 
     61     public State getState() {
     62         return state;
     63     }
     64  
     65     public String getLocation() {
     66         return location;
     67     }
     68  
     69     public State getSoldOutState() {
     70         return soldOutState;
     71     }
     72 
     73     public State getNoQuarterState() {
     74         return noQuarterState;
     75     }
     76 
     77     public State getHasQuarterState() {
     78         return hasQuarterState;
     79     }
     80 
     81     public State getSoldState() {
     82         return soldState;
     83     }
     84 
     85     public State getWinnerState() {
     86         return winnerState;
     87     }
     88  
     89     public String toString() {
     90         StringBuffer result = new StringBuffer();
     91         result.append("
    Mighty Gumball, Inc.");
     92         result.append("
    Java-enabled Standing Gumball Model #2004");
     93         result.append("
    Inventory: " + count + " gumball");
     94         if (count != 1) {
     95             result.append("s");
     96         }
     97         result.append("
    ");
     98         result.append("Machine is " + state + "
    ");
     99         return result.toString();
    100     }
    101 }

    2.

     1 package headfirst.designpatterns.proxy.gumballmonitor;
     2  
     3 public class GumballMonitor {
     4     GumballMachine machine;
     5  
     6     public GumballMonitor(GumballMachine machine) {
     7         this.machine = machine;
     8     }
     9  
    10     public void report() {
    11         System.out.println("Gumball Machine: " + machine.getLocation());
    12         System.out.println("Current inventory: " + machine.getCount() + " gumballs");
    13         System.out.println("Current state: " + machine.getState());
    14     }
    15 }

    3.

     1 package headfirst.designpatterns.proxy.gumballmonitor;
     2 
     3 public class GumballMachineTestDrive {
     4 
     5     public static void main(String[] args) {
     6         int count = 0;
     7 
     8         if (args.length < 2) {
     9             System.out.println("GumballMachine <name> <inventory>");
    10             System.exit(1);
    11         }
    12 
    13         try {
    14             count = Integer.parseInt(args[1]);
    15         } catch (Exception e) {
    16             e.printStackTrace();
    17             System.exit(1);
    18         }
    19         GumballMachine gumballMachine = new GumballMachine(args[0], count);
    20 
    21         GumballMonitor monitor = new GumballMonitor(gumballMachine);
    22 
    23  
    24         System.out.println(gumballMachine);
    25 
    26         gumballMachine.insertQuarter();
    27         gumballMachine.turnCrank();
    28         gumballMachine.insertQuarter();
    29         gumballMachine.turnCrank();
    30 
    31         System.out.println(gumballMachine);
    32 
    33         gumballMachine.insertQuarter();
    34         gumballMachine.turnCrank();
    35         gumballMachine.insertQuarter();
    36         gumballMachine.turnCrank();
    37 
    38         System.out.println(gumballMachine);
    39 
    40         gumballMachine.insertQuarter();
    41         gumballMachine.turnCrank();
    42         gumballMachine.insertQuarter();
    43         gumballMachine.turnCrank();
    44 
    45         System.out.println(gumballMachine);
    46 
    47         gumballMachine.insertQuarter();
    48         gumballMachine.turnCrank();
    49         gumballMachine.insertQuarter();
    50         gumballMachine.turnCrank();
    51 
    52         System.out.println(gumballMachine);
    53 
    54         gumballMachine.insertQuarter();
    55         gumballMachine.turnCrank();
    56         gumballMachine.insertQuarter();
    57         gumballMachine.turnCrank();
    58 
    59         System.out.println(gumballMachine);
    60 
    61         monitor.report();
    62     }
    63 }

    4.

     1 package headfirst.designpatterns.proxy.gumballmonitor;
     2 
     3 
     4 import java.util.Random;
     5 
     6 public class HasQuarterState implements State {
     7     private static final long serialVersionUID = 2L;
     8     Random randomWinner = new Random(System.currentTimeMillis());
     9     GumballMachine gumballMachine;
    10  
    11     public HasQuarterState(GumballMachine gumballMachine) {
    12         this.gumballMachine = gumballMachine;
    13     }
    14   
    15     public void insertQuarter() {
    16         System.out.println("You can't insert another quarter");
    17     }
    18  
    19     public void ejectQuarter() {
    20         System.out.println("Quarter returned");
    21         gumballMachine.setState(gumballMachine.getNoQuarterState());
    22     }
    23  
    24     public void turnCrank() {
    25         System.out.println("You turned...");
    26         int winner = randomWinner.nextInt(10);
    27         if (winner == 0) {
    28             gumballMachine.setState(gumballMachine.getWinnerState());
    29         } else {
    30             gumballMachine.setState(gumballMachine.getSoldState());
    31         }
    32     }
    33 
    34     public void dispense() {
    35         System.out.println("No gumball dispensed");
    36     }
    37  
    38     public String toString() {
    39         return "waiting for turn of crank";
    40     }
    41 }

    5.

     1 package headfirst.designpatterns.proxy.gumballmonitor;
     2 
     3 public class NoQuarterState implements State {
     4     private static final long serialVersionUID = 2L;
     5     GumballMachine gumballMachine;
     6  
     7     public NoQuarterState(GumballMachine gumballMachine) {
     8         this.gumballMachine = gumballMachine;
     9     }
    10  
    11     public void insertQuarter() {
    12         System.out.println("You inserted a quarter");
    13         gumballMachine.setState(gumballMachine.getHasQuarterState());
    14     }
    15  
    16     public void ejectQuarter() {
    17         System.out.println("You haven't inserted a quarter");
    18     }
    19  
    20     public void turnCrank() {
    21         System.out.println("You turned, but there's no quarter");
    22      }
    23  
    24     public void dispense() {
    25         System.out.println("You need to pay first");
    26     } 
    27  
    28     public String toString() {
    29         return "waiting for quarter";
    30     }
    31 }

    三、远程代理(使用RMI)

    1.

    1 package headfirst.designpatterns.proxy.gumball;
    2 
    3 import java.rmi.*;
    4  
    5 public interface GumballMachineRemote extends Remote {
    6     public int getCount() throws RemoteException;
    7     public String getLocation() throws RemoteException;
    8     public State getState() throws RemoteException;
    9 }

    2.

     1 package headfirst.designpatterns.proxy.gumball;
     2 
     3 import java.io.*;
     4  
     5 //Then we just extend the Serializable interface
     6 //now State in all the subclasses can be transferred over the network.
     7 public interface State extends Serializable {
     8     public void insertQuarter();
     9     public void ejectQuarter();
    10     public void turnCrank();
    11     public void dispense();
    12 }

    3.

     1 package headfirst.designpatterns.proxy.gumball;
     2 
     3 public class NoQuarterState implements State {
     4     private static final long serialVersionUID = 2L;
     5     
     6     //in each implementation of State, we
     7 //    add the transient keyword to the
     8 //    GumballMachine instance variable. This
     9 //    tells the JVM not to serialize this field.
    10 //    Note that this can be slightly dangerous
    11 //    if you try to access this field once its
    12 //    been serialized and transferred.
    13     transient GumballMachine gumballMachine;
    14  
    15     public NoQuarterState(GumballMachine gumballMachine) {
    16         this.gumballMachine = gumballMachine;
    17     }
    18  
    19     public void insertQuarter() {
    20         System.out.println("You inserted a quarter");
    21         gumballMachine.setState(gumballMachine.getHasQuarterState());
    22     }
    23  
    24     public void ejectQuarter() {
    25         System.out.println("You haven't inserted a quarter");
    26     }
    27  
    28     public void turnCrank() {
    29         System.out.println("You turned, but there's no quarter");
    30      }
    31  
    32     public void dispense() {
    33         System.out.println("You need to pay first");
    34     } 
    35  
    36     public String toString() {
    37         return "waiting for quarter";
    38     }
    39 }

    4.

      1 package headfirst.designpatterns.proxy.gumball;
      2 
      3 import java.rmi.*;
      4 import java.rmi.server.*;
      5 
      6 //GumballMachine is going to subclass the UnicastRemoteObject;
      7 //this gives it the ability to act as a remote service.
      8 public class GumballMachine
      9         extends UnicastRemoteObject implements GumballMachineRemote 
     10 {
     11     private static final long serialVersionUID = 2L;
     12     State soldOutState;
     13     State noQuarterState;
     14     State hasQuarterState;
     15     State soldState;
     16     State winnerState;
     17  
     18     State state = soldOutState;
     19     int count = 0;
     20      String location;
     21 
     22     public GumballMachine(String location, int numberGumballs) throws RemoteException {
     23         soldOutState = new SoldOutState(this);
     24         noQuarterState = new NoQuarterState(this);
     25         hasQuarterState = new HasQuarterState(this);
     26         soldState = new SoldState(this);
     27         winnerState = new WinnerState(this);
     28 
     29         this.count = numberGumballs;
     30          if (numberGumballs > 0) {
     31             state = noQuarterState;
     32         } 
     33         this.location = location;
     34     }
     35  
     36  
     37     public void insertQuarter() {
     38         state.insertQuarter();
     39     }
     40  
     41     public void ejectQuarter() {
     42         state.ejectQuarter();
     43     }
     44  
     45     public void turnCrank() {
     46         state.turnCrank();
     47         state.dispense();
     48     }
     49 
     50     void setState(State state) {
     51         this.state = state;
     52     }
     53  
     54     void releaseBall() {
     55         System.out.println("A gumball comes rolling out the slot...");
     56         if (count != 0) {
     57             count = count - 1;
     58         }
     59     }
     60 
     61     public void refill(int count) {
     62         this.count = count;
     63         state = noQuarterState;
     64     }
     65  
     66     public int getCount() {
     67         return count;
     68     }
     69  
     70     public State getState() {
     71         return state;
     72     }
     73  
     74     public String getLocation() {
     75         return location;
     76     }
     77   
     78     public State getSoldOutState() {
     79         return soldOutState;
     80     }
     81 
     82     public State getNoQuarterState() {
     83         return noQuarterState;
     84     }
     85 
     86     public State getHasQuarterState() {
     87         return hasQuarterState;
     88     }
     89 
     90     public State getSoldState() {
     91         return soldState;
     92     }
     93 
     94     public State getWinnerState() {
     95         return winnerState;
     96     }
     97  
     98     public String toString() {
     99         StringBuffer result = new StringBuffer();
    100         result.append("
    Mighty Gumball, Inc.");
    101         result.append("
    Java-enabled Standing Gumball Model #2014");
    102         result.append("
    Inventory: " + count + " gumball");
    103         if (count != 1) {
    104             result.append("s");
    105         }
    106         result.append("
    ");
    107         result.append("Machine is " + state + "
    ");
    108         return result.toString();
    109     }
    110 }

    5.Registering with the RMI registry

     1 package headfirst.designpatterns.proxy.gumball;
     2 import java.rmi.*;
     3 
     4 public class GumballMachineTestDrive {
     5  
     6     public static void main(String[] args) {
     7         GumballMachineRemote gumballMachine = null;
     8         int count;
     9 
    10         if (args.length < 2) {
    11             System.out.println("GumballMachine <name> <inventory>");
    12              System.exit(1);
    13         }
    14 
    15         try {
    16             count = Integer.parseInt(args[1]);
    17 
    18             gumballMachine = 
    19                 new GumballMachine(args[0], count);
    20             Naming.rebind("//" + args[0] + "/gumballmachine", gumballMachine);
    21         } catch (Exception e) {
    22             e.printStackTrace();
    23         }
    24     }
    25 }

    6.

     1 package headfirst.designpatterns.proxy.gumball;
     2 
     3 import java.rmi.*;
     4  
     5 public class GumballMonitor {
     6     //Now we’re going to rely on the remote interface 
     7     //rather than the concrete GumballMachine class.
     8     GumballMachineRemote machine;
     9  
    10     public GumballMonitor(GumballMachineRemote machine) {
    11         this.machine = machine;
    12     }
    13  
    14     public void report() {
    15         try {
    16             System.out.println("Gumball Machine: " + machine.getLocation());
    17             System.out.println("Current inventory: " + machine.getCount() + " gumballs");
    18             System.out.println("Current state: " + machine.getState());
    19         } catch (RemoteException e) {
    20             e.printStackTrace();
    21         }
    22     }
    23 }

    7.

     1 package headfirst.designpatterns.proxy.gumball;
     2 
     3 import java.rmi.*;
     4  
     5 public class GumballMonitorTestDrive {
     6  
     7     public static void main(String[] args) {
     8         String[] location = {"rmi://santafe.mightygumball.com/gumballmachine",
     9                              "rmi://boulder.mightygumball.com/gumballmachine",
    10                              "rmi://seattle.mightygumball.com/gumballmachine"}; 
    11         
    12         if (args.length >= 0)
    13         {
    14             location = new String[1];
    15             location[0] = "rmi://" + args[0] + "/gumballmachine";
    16         }
    17         
    18         GumballMonitor[] monitor = new GumballMonitor[location.length];
    19         
    20         
    21         
    22         for (int i=0;i < location.length; i++) {
    23             try {
    24                 //This returns a proxy to the remote Gumball Machine 
    25                 //(or throws an exception if one can’t be located).
    26                    GumballMachineRemote machine = 
    27                         (GumballMachineRemote) Naming.lookup(location[i]);
    28                    //Naming.lookup() is a static method in the RMI package
    29                    //that takes a location and service name and looks it up in the
    30                    //rmiregistry at that location.
    31                    monitor[i] = new GumballMonitor(machine);
    32                 System.out.println(monitor[i]);
    33             } catch (Exception e) {
    34                 e.printStackTrace();
    35             }
    36         }
    37  
    38         for(int i=0; i < monitor.length; i++) {
    39             monitor[i].report();
    40         }
    41     }
    42 }

    By invoking methods on the proxy, a remote call is made across the wire and a String, an integer and a State object are returned. Because we are using a proxy, the GumballMonitor doesn’t know,or care, that calls are remote (other than having to worry about remote exceptions).

     

    四.虚拟代理(代理create代价高的对象)分析

    1.需求:要做一个显示cd封面的应用,封面是访问网络得到,为了当在访问网络获取图片较慢时,卡住程序,使用代理模式,但图片还没下载完时显示文字提示信息,但下载完后就显示图片

    2.How ImageProxy is going to work:

    (1)ImageProxy first creates an ImageIcon and starts loading it from a network URL.

    (2)While the bytes of the image are being retrieved,ImageProxy displays “Loading CD cover, please wait...”.
    (3)When the image is fully loaded, ImageProxy delegates all method calls to the image icon, including paintIcon(), getWidth() and getHeight().
    (4)If the user requests a new image, we’ll create a new proxy and start the process over.

    3.

    4.

    五、虚拟代理的实现

    1.

     1 package headfirst.designpatterns.proxy.virtualproxy;
     2 
     3 import java.net.*;
     4 import java.awt.*;
     5 import javax.swing.*;
     6 
     7 class ImageProxy implements Icon {
     8     volatile ImageIcon imageIcon;
     9     final URL imageURL;
    10     Thread retrievalThread;
    11     boolean retrieving = false;
    12      
    13     public ImageProxy(URL url) { imageURL = url; }
    14      
    15     public int getIconWidth() {
    16         if (imageIcon != null) {
    17             return imageIcon.getIconWidth();
    18         } else {
    19             return 800;
    20         }
    21     }
    22  
    23     public int getIconHeight() {
    24         if (imageIcon != null) {
    25             return imageIcon.getIconHeight();
    26         } else {
    27             return 600;
    28         }
    29     }
    30     
    31     synchronized void setImageIcon(ImageIcon imageIcon) {
    32         this.imageIcon = imageIcon;
    33     }
    34      
    35     //This method is called when it’s time to paint the icon on the screen.
    36     public void paintIcon(final Component c, Graphics  g, int x,  int y) {
    37         //If we’ve got an icon already, we go ahead and tell it to paint itself.
    38         if (imageIcon != null) {
    39             imageIcon.paintIcon(c, g, x, y);
    40         } else {
    41             //Otherwise we display the “loading” message.
    42             g.drawString("Loading CD cover, please wait...", x+300, y+190);
    43             if (!retrieving) {
    44                 retrieving = true;
    45 
    46                 retrievalThread = new Thread(new Runnable() {
    47                     public void run() {
    48                         try {
    49                             setImageIcon(new ImageIcon(imageURL, "CD Cover"));
    50                             c.repaint();
    51                         } catch (Exception e) {
    52                             e.printStackTrace();
    53                         }
    54                     }
    55                 });
    56                 retrievalThread.start();
    57             }
    58         }
    59     }
    60 }

    2.

     1 package headfirst.designpatterns.proxy.virtualproxy;
     2 
     3 import java.awt.*;
     4 import javax.swing.*;
     5 
     6 class ImageComponent extends JComponent {
     7     private static final long serialVersionUID = 1L;
     8     private Icon icon;
     9 
    10     public ImageComponent(Icon icon) {
    11         this.icon = icon;
    12     }
    13 
    14     public void setIcon(Icon icon) {
    15         this.icon = icon;
    16     }
    17 
    18     public void paintComponent(Graphics g) {
    19         super.paintComponent(g);
    20         int w = icon.getIconWidth();
    21         int h = icon.getIconHeight();
    22         int x = (800 - w)/2;
    23         int y = (600 - h)/2;
    24         icon.paintIcon(this, g, x, y);
    25     }
    26 }

    3.

     1 package headfirst.designpatterns.proxy.virtualproxy;
     2 
     3 import java.awt.event.ActionEvent;
     4 import java.awt.event.ActionListener;
     5 import java.net.*;
     6 import javax.swing.*;
     7 import java.util.*;
     8 
     9 public class ImageProxyTestDrive {
    10     ImageComponent imageComponent;
    11     JFrame frame = new JFrame("CD Cover Viewer");
    12     JMenuBar menuBar;
    13     JMenu menu;
    14     Hashtable<String, String> cds = new Hashtable<String, String>();
    15 
    16     public static void main (String[] args) throws Exception {
    17         ImageProxyTestDrive testDrive = new ImageProxyTestDrive();
    18     }
    19 
    20     public ImageProxyTestDrive() throws Exception{
    21         cds.put("Buddha Bar","http://images.amazon.com/images/P/B00009XBYK.01.LZZZZZZZ.jpg");
    22         cds.put("Ima","http://images.amazon.com/images/P/B000005IRM.01.LZZZZZZZ.jpg");
    23         cds.put("Karma","http://images.amazon.com/images/P/B000005DCB.01.LZZZZZZZ.gif");
    24         cds.put("MCMXC A.D.","http://images.amazon.com/images/P/B000002URV.01.LZZZZZZZ.jpg");
    25         cds.put("Northern Exposure","http://images.amazon.com/images/P/B000003SFN.01.LZZZZZZZ.jpg");
    26         cds.put("Selected Ambient Works, Vol. 2","http://images.amazon.com/images/P/B000002MNZ.01.LZZZZZZZ.jpg");
    27 
    28         URL initialURL = new URL((String)cds.get("Selected Ambient Works, Vol. 2"));
    29         menuBar = new JMenuBar();
    30         menu = new JMenu("Favorite CDs");
    31         menuBar.add(menu);
    32         frame.setJMenuBar(menuBar);
    33 
    34         for (Enumeration<String> e = cds.keys(); e.hasMoreElements();) {
    35             String name = (String)e.nextElement();
    36             JMenuItem menuItem = new JMenuItem(name);
    37             menu.add(menuItem); 
    38             menuItem.addActionListener(new ActionListener() {
    39                 @Override
    40                 public void actionPerformed(ActionEvent e) {
    41                     imageComponent.setIcon(new ImageProxy(getCDUrl(e.getActionCommand())));
    42                     frame.repaint();
    43                 }
    44             }); 
    45         }
    46 
    47         // set up frame and menus
    48 
    49         Icon icon = new ImageProxy(initialURL);
    50         imageComponent = new ImageComponent(icon);
    51         frame.getContentPane().add(imageComponent);
    52         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    53         frame.setSize(800,600);
    54         frame.setVisible(true);
    55 
    56     }
    57 
    58     URL getCDUrl(String name) {
    59         try {
    60             return new URL((String)cds.get(name));
    61         } catch (MalformedURLException e) {
    62             e.printStackTrace();
    63             return null;
    64         }
    65     }
    66 }

    六、动态代理分析

    1.

    2.The job of the InvocationHandler is to respond to any method calls on the proxy. Think of the InvocationHandler as the

    object the Proxy asks to do all the real work after it’s received the method calls.

    3.The Decorator Pattern adds behavior to an object, while a Proxy controls access.

    七、动态代理实现

    1.

     1 package headfirst.designpatterns.proxy.javaproxy;
     2 
     3 public interface PersonBean {
     4  
     5     String getName();
     6     String getGender();
     7     String getInterests();
     8     int getHotOrNotRating();
     9  
    10     void setName(String name);
    11     void setGender(String gender);
    12     void setInterests(String interests);
    13     void setHotOrNotRating(int rating); 
    14  
    15 }

    2.

     1 package headfirst.designpatterns.proxy.javaproxy;
     2 
     3 public class PersonBeanImpl implements PersonBean {
     4     String name;
     5     String gender;
     6     String interests;
     7     int rating;
     8     int ratingCount = 0;
     9   
    10     public String getName() {
    11         return name;    
    12     } 
    13   
    14     public String getGender() {
    15         return gender;
    16     }
    17   
    18     public String getInterests() {
    19         return interests;
    20     }
    21    
    22     public int getHotOrNotRating() {
    23         if (ratingCount == 0) return 0;
    24         return (rating/ratingCount);
    25     }
    26   
    27  
    28     public void setName(String name) {
    29         this.name = name;
    30     }
    31  
    32     public void setGender(String gender) {
    33         this.gender = gender;
    34     } 
    35   
    36     public void setInterests(String interests) {
    37         this.interests = interests;
    38     } 
    39   
    40     public void setHotOrNotRating(int rating) {
    41         this.rating += rating;    
    42         ratingCount++;
    43     }
    44 }

    3.

     1 package headfirst.designpatterns.proxy.javaproxy;
     2  
     3 import java.lang.reflect.*;
     4  
     5 public class NonOwnerInvocationHandler implements InvocationHandler { 
     6     PersonBean person;
     7  
     8     public NonOwnerInvocationHandler(PersonBean person) {
     9         this.person = person;
    10     }
    11  
    12     public Object invoke(Object proxy, Method method, Object[] args) 
    13             throws IllegalAccessException {
    14   
    15         try {
    16             if (method.getName().startsWith("get")) {
    17                 return method.invoke(person, args);
    18                } else if (method.getName().equals("setHotOrNotRating")) {
    19                 return method.invoke(person, args);
    20             } else if (method.getName().startsWith("set")) {
    21                 throw new IllegalAccessException();
    22             } 
    23         } catch (InvocationTargetException e) {
    24             e.printStackTrace();
    25         } 
    26         return null;
    27     }
    28 }

    4.

     1 package headfirst.designpatterns.proxy.javaproxy;
     2  
     3 import java.lang.reflect.*;
     4  
     5 public class OwnerInvocationHandler implements InvocationHandler { 
     6     PersonBean person;
     7  
     8     public OwnerInvocationHandler(PersonBean person) {
     9         this.person = person;
    10     }
    11  
    12     public Object invoke(Object proxy, Method method, Object[] args) 
    13             throws IllegalAccessException {
    14   
    15         try {
    16             if (method.getName().startsWith("get")) {
    17                 return method.invoke(person, args);
    18                } else if (method.getName().equals("setHotOrNotRating")) {
    19                 throw new IllegalAccessException();
    20             } else if (method.getName().startsWith("set")) {
    21                 return method.invoke(person, args);
    22             } 
    23         } catch (InvocationTargetException e) {
    24             e.printStackTrace();
    25         } 
    26         return null;
    27     }
    28 }

    5.

     1 package headfirst.designpatterns.proxy.javaproxy;
     2 
     3 import java.lang.reflect.*;
     4 import java.util.*;
     5 
     6 public class MatchMakingTestDrive {
     7     HashMap<String, PersonBean> datingDB = new HashMap<String, PersonBean>();
     8      
     9     public static void main(String[] args) {
    10         MatchMakingTestDrive test = new MatchMakingTestDrive();
    11         test.drive();
    12     }
    13  
    14     public MatchMakingTestDrive() {
    15         initializeDatabase();
    16     }
    17 
    18     public void drive() {
    19         PersonBean joe = getPersonFromDatabase("Joe Javabean"); 
    20         PersonBean ownerProxy = getOwnerProxy(joe);
    21         System.out.println("Name is " + ownerProxy.getName());
    22         ownerProxy.setInterests("bowling, Go");
    23         System.out.println("Interests set from owner proxy");
    24         try {
    25             ownerProxy.setHotOrNotRating(10);
    26         } catch (Exception e) {
    27             System.out.println("Can't set rating from owner proxy");
    28         }
    29         System.out.println("Rating is " + ownerProxy.getHotOrNotRating());
    30 
    31         PersonBean nonOwnerProxy = getNonOwnerProxy(joe);
    32         System.out.println("Name is " + nonOwnerProxy.getName());
    33         try {
    34             nonOwnerProxy.setInterests("bowling, Go");
    35         } catch (Exception e) {
    36             System.out.println("Can't set interests from non owner proxy");
    37         }
    38         nonOwnerProxy.setHotOrNotRating(3);
    39         System.out.println("Rating set from non owner proxy");
    40         System.out.println("Rating is " + nonOwnerProxy.getHotOrNotRating());
    41     }
    42 
    43     PersonBean getOwnerProxy(PersonBean person) {
    44          
    45         return (PersonBean) Proxy.newProxyInstance( 
    46                 person.getClass().getClassLoader(),
    47                 person.getClass().getInterfaces(),
    48                 new OwnerInvocationHandler(person));
    49     }
    50 
    51     PersonBean getNonOwnerProxy(PersonBean person) {
    52         
    53         return (PersonBean) Proxy.newProxyInstance(
    54                 person.getClass().getClassLoader(),
    55                 person.getClass().getInterfaces(),
    56                 new NonOwnerInvocationHandler(person));
    57     }
    58 
    59     PersonBean getPersonFromDatabase(String name) {
    60         return (PersonBean)datingDB.get(name);
    61     }
    62 
    63     void initializeDatabase() {
    64         PersonBean joe = new PersonBeanImpl();
    65         joe.setName("Joe Javabean");
    66         joe.setInterests("cars, computers, music");
    67         joe.setHotOrNotRating(7);
    68         datingDB.put(joe.getName(), joe);
    69 
    70         PersonBean kelly = new PersonBeanImpl();
    71         kelly.setName("Kelly Klosure");
    72         kelly.setInterests("ebay, movies, music");
    73         kelly.setHotOrNotRating(6);
    74         datingDB.put(kelly.getName(), kelly);
    75     }
    76 }

    6.

  • 相关阅读:
    C#代码中函数调用相关问题
    C#语言编写代码时常用的三大循环
    c#语言中的类型转换
    tesseract_vs2015工具包使用
    Halcon除法
    halcon批量读取图片
    halcon分离路径名称
    Halcon旋转图片的研究
    关于Haclon使用GPU加速的代码实例
    OpenCV代码:画出轮廓的外接矩形,和中心点
  • 原文地址:https://www.cnblogs.com/shamgod/p/5266125.html
Copyright © 2011-2022 走看看