代理模式

Posted sansuiwantong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了代理模式相关的知识,希望对你有一定的参考价值。

1.远程代理:隐藏远程代理的事实

   虚拟代理:避免加载大对象GUI挂起

   保护代理:避免不想要的访问;

   动态代理:java本身实现了proxy,InvacationHandler响应,

                  动态 不是 指运行时将它实例化并和handle关联, 运行时才将它的类创建出来,

                  开始执行还没有proxy类,根据需要从接口集创建

2.代码

C++

 1 //proxy c++
 2 #include <iostream>
 3 #include <string>
 4 using namespace std;
 5 
 6 class Interface{
 7 public:
 8     virtual void Request() = 0;
 9 };
10 
11 class RealClass : public Interface{
12 public:
13     virtual void Request(){
14         cout<<"Real request"<<endl;
15     }
16 };
17 
18 class ProxyClass : public Interface{
19 public:
20     virtual void Request(){
21         m_realClass = new RealClass();
22         m_realClass->Request();
23         delete m_realClass;
24     }
25 private:
26     RealClass * m_realClass;
27 };
28 
29 int main(){
30     ProxyClass* proxy = new ProxyClass();
31     proxy->Request();
32     return 0;
33 }

技术图片

 Java

(1)rmiExample

1 //interface remote;
2 import java.rmi.*;
3 
4 public interface MyRemote extends Remote{
5     public String sayHello() throws RemoteException;
6 }
 1 //proxy java server
 2 import java.rmi.*;
 3 import java.rmi.server.*;
 4 
 5 
 6 class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{
 7     public MyRemoteImpl() throws RemoteException{}
 8     public String sayHello(){
 9         return "Server says,‘Hey‘";
10     }
11 }
12 
13 public class proxyServer{
14     public static void main(String[] args){
15         try{
16             MyRemote service = new MyRemoteImpl();
17             Naming.rebind("RemoteHello",service);
18         }catch(Exception ex){
19             ex.printStackTrace();
20         }
21     } 
22 }
 1 //proxy java client
 2 import java.rmi.*;
 3 
 4 public  class proxyClient{
 5     public static void main(String[] args){
 6         new proxyClient().go();
 7     }
 8     public void go(){
 9         try{
10             MyRemote service = (MyRemote) Naming.lookup("rmi://127.0.0.1/RemoteHello");
11             String s = service.sayHello();
12             System.out.println(s);
13         }catch(Exception ex){
14             ex.printStackTrace();
15         }
16     }
17 }
1 rmic MyRemoteImpl
2 rmiregistry
3 java proxyServer
4 java proxyClient

技术图片

 (2) 远程代理

 1 //proxy GumballMachineRemote server
 2 import java.rmi.*;
 3 import java.io.*;
 4 import java.rmi.server.*;
 5 
 6 interface State extends Serializable{  //Serializable
 7 /*
 8     public void insertQuarter();
 9     public void ejectQuarter();
10     public void turnCrank();
11     public void dispense();
12 */
13 }
14 
15 class NoQuarterState implements State{
16     transient GumballMachine gumballMachine; //transient
17     
18 }
19 
20 interface GumballMachineRemote extends Remote{
21     public int    getCount()    throws RemoteException;
22     public String getLocation() throws RemoteException;
23     public State  getState()    throws RemoteException;
24 }
25 
26 class GumballMachine extends UnicastRemoteObject implements GumballMachineRemote{
27     private int    count;
28     private String location;
29     private State  state;
30     
31     public GumballMachine(String location,int numberGumballs) throws RemoteException{
32         this.location = location;
33         this.count    = numberGumballs;
34     }
35     public int getCount(){
36         return this.count;
37     }
38     public State getState(){
39         return this.state;
40     }
41     public String getLocation(){
42         return this.location;
43     }
44     public void dispense(){
45         System.out.println("null");
46     }
47 }
48 
49 public class GumballMachineDrive{
50     public static void main(String[] args){
51 
52         if(args.length < 2){
53             System.out.println("java GumballMachineDrive location 2");
54             System.exit(1);
55         }
56         
57         try{
58             int count = Integer.parseInt(args[1]);
59             GumballMachine server = new GumballMachine(args[0],count);
60             Naming.rebind(args[0],server);    
61         }catch(Exception ex){
62             ex.printStackTrace();
63         }
64     }
65 }
 1 //proxy GumballMachineRemote client
 2 import java.rmi.*;
 3 class GumballMonitor{
 4     GumballMachineRemote machine;
 5     public GumballMonitor(GumballMachineRemote machine){
 6         this.machine = machine;
 7     }
 8     public void report(){
 9         try{
10             System.out.println("Machine:"   + machine.getLocation());
11             System.out.println("Inventory:" + machine.getCount());
12         }catch(RemoteException e){
13             e.printStackTrace();
14         }
15     }
16 }
17 
18 public class GumballMachineClient{
19     public static void main(String[] args){
20         if(args.length < 1){
21             System.out.println("java GumballMachineClient localtion");
22             System.exit(1);
23         }
24         try{
25             GumballMachineRemote machine = (GumballMachineRemote)Naming.lookup(args[0]);        
26             GumballMonitor monitor = new GumballMonitor(machine);
27             monitor.report();
28         }catch(Exception e){
29             e.printStackTrace();
30         }
31     }
32 }

技术图片

 (3) 虚拟代理

  1 //java virtual Proxy load Image
  2 import java.net.*;
  3 import java.awt.*;
  4 import javax.swing.*;
  5 import java.util.*;;
  6 
  7 class ImageComponent extends JComponent{
  8     private Icon icon;
  9     public ImageComponent(Icon icon){
 10         this.icon = icon;
 11     }
 12     public void setIcon(Icon icon){
 13         this.icon = icon;
 14     }
 15     public void paintComponent(Graphics g){
 16         super.paintComponent(g);
 17         int w = icon.getIconWidth();
 18         int h = icon.getIconHeight();
 19         int x = (800 - w)/2;
 20         int y = (600 - h)/2;
 21         icon.paintIcon(this,g,x,y);
 22     }
 23 }
 24 
 25 class ImageProxy implements Icon{
 26     ImageIcon imageIcon;
 27     String imageURL;
 28     Thread retrievalThread;
 29     boolean retrieving = false;
 30     
 31     public ImageProxy(String url){ imageURL = url; }
 32     public int getIconWidth(){
 33         if(imageIcon != null){
 34             return imageIcon.getIconWidth();//
 35         }else{
 36             return 800;
 37         }
 38     }
 39     public int getIconHeight(){
 40         if(imageIcon != null){
 41             return imageIcon.getIconHeight();
 42         }else{
 43             return 600;
 44         }
 45     }
 46     public void paintIcon(final Component c,Graphics g,int x,int y){
 47         if(imageIcon != null){
 48             imageIcon.paintIcon(c,g,x,y);
 49         }else{
 50             g.drawString("Loading...",x+300,y+190);
 51             if(!retrieving){
 52                 retrieving = true;
 53                 retrievalThread = new Thread(
 54                     ()-> {
 55                         try{
 56                             imageIcon = new ImageIcon(getUrl(imageURL),"CD Cover");//need getUrl again
 57                             if(imageIcon.getImageLoadStatus() == MediaTracker.COMPLETE) {
 58                                 c.repaint();
 59                             }else{
 60                                 System.out.println("error: load image fail,disconnected? move frame to repaint");
 61 
 62                                 retrieving = false;
 63                                 imageIcon = null;
 64                             }
 65                         }catch(Exception e){
 66                             e.printStackTrace();
 67                         }
 68                         System.out.println("finish");
 69                     });
 70                 retrievalThread.start();
 71             }
 72         }
 73     }
 74     private URL getUrl(String name){
 75         try{
 76             return new URL(name);
 77         }catch(MalformedURLException e){
 78             e.printStackTrace();
 79             return null;
 80         }
 81     }
 82 }
 83 
 84 public class virtualProxy{
 85     ImageComponent imageComponent;
 86     JFrame frame = new JFrame("A virtual proxy demo");
 87 
 88     public static void main(String[] args) throws Exception{
 89         virtualProxy testProxy = new virtualProxy();
 90     }
 91     public  virtualProxy() throws Exception{
 92         
 93         String initialURL = "http://images.amazon.com/images/P/B000005IRM.01.LZZZZZZZ.jpg";
 94         
 95         Icon icon = new ImageProxy(initialURL);
 96         imageComponent = new ImageComponent(icon);
 97         frame.getContentPane().add(imageComponent);
 98         frame.setSize(800,600);
 99         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
100         frame.setVisible(true);
101     }
102 }

技术图片

 

 (4) 保护代理

 1 //protect proxy java
 2 //use InvocationHandler
 3 import java.lang.reflect.*;
 4 
 5 interface PersonBean{
 6     String getName();
 7     int getHotOrNotRating();
 8     void setName(String name);
 9     void setHotOrNotRating(int rating);
10 }
11 
12 class PersonBeanImpl implements PersonBean{
13     String name;
14     int rating;
15     public String getName(){
16         return name;
17     }
18     public int getHotOrNotRating(){
19         return rating;
20     }
21     public void setName(String name){
22         this.name = name;
23     }
24     public void setHotOrNotRating(int rating){
25         this.rating = rating;
26     }
27 }
28 
29 class OwnerInvocationHandler implements InvocationHandler{
30     PersonBean person;
31     public OwnerInvocationHandler(PersonBean person){
32         this.person = person;
33     }
34     public Object invoke(Object proxy,Method method,Object[] args)
35             throws IllegalAccessException{
36                 try{
37                 if(method.getName().startsWith("get")){
38                     return method.invoke(person,args);
39                 }else if(method.getName().equals("setHotOrNotRating")){
40                     throw new IllegalAccessException();
41                 }else if(method.getName().startsWith("set")){
42                     return method.invoke(person,args);
43                 }
44             }catch(InvocationTargetException e){
45                 e.printStackTrace();
46             }
47             return null;
48     }
49 }
50 
51 public class protectProxy{
52     public static void main(String[] args){
53         PersonBean joe = new PersonBeanImpl();
54         joe.setName("joe");
55         PersonBean ownerproxy = getOwnerProxy(joe);
56         try{
57             ownerproxy.setHotOrNotRating(10);
58         }catch(Exception e){
59             System.out.println("can not set");
60         }
61         ownerproxy.setName("joe_change");
62         System.out.println(joe.getName());
63     }
64     
65     static PersonBean getOwnerProxy(PersonBean person){
66         return (PersonBean)Proxy.newProxyInstance(
67                 person.getClass().getClassLoader(),
68                 person.getClass().getInterfaces(),
69                 new OwnerInvocationHandler(person) );
70     }
71 }

技术图片

 3.杂记

  3.1.

       防火墙     代理(FireWall Proxy)

       智能引用  代理(Smart Reference Proxy)--- 引用计数

       缓存         代理(Caching Proxy)              --- web 服务暂存

       同步         代理(Synchronization Proxy)  --- javaSpace 分散式环境

       复杂隐藏  代理(Complex Hiding Proxy)  --- 也称 外观代理(Facade Proxy)

       写是复用  代理(Copy-on-Write Proxy)    --- 虚拟代理变体

  3.2

       stub             --- 桩

       skeleton       --- 骨架 

       primitive       --- 原语类型

       Serialization --- 可序列化类型,远程方法的返回值必须是可序列化类型

 

以上是关于代理模式的主要内容,如果未能解决你的问题,请参考以下文章

scrapy按顺序启动多个爬虫代码片段(python3)

用于从 cloudkit 检索单列的代码模式/片段

java代码实现设计模式之代理模式

代理模式(静态代理动态代理)代码实战(详细)

Java设计模式-代理模式之动态代理(附源代码分析)

代理模式(静态代理)