Design Patterns of the Proxy Pattern (Proxy Pattern) Introduction of the Proxy Pattern Example Programs of the Proxy Pattern Proxy Pattern Analysis


  • Introduction of the proxy model
  • Example program for the proxy model
  • Analysis of the proxy model

Introduction of the proxy model

Proxy means agent and refers to a person who performs work in place of someone else. When the work does not necessarily need to be done in person, an agent can be found to do it. In the agency model, however, it is often the other way around; usually the agent comes across the work and leaves it to the object being represented, with the agent only doing some preparatory or closing work. If the reader understands the spring framework, then you will know that aop is also cutter-oriented programming is actually using the dynamic proxy pattern, which allows the proxy object to focus on completing their own work, while the proxy object can work before the logging, time calculations, logging after the work, closing work and other additional functions that need to be done formally when the work is left to the proxy to do. It's like sticking two knives into the front and back of this proxied object. So the image is called cut-oriented programming. For more information on the dynamic and static proxy patterns, interested readers can refer to another blog post by the author at Java dynamic vs. static proxieshttp://www.jianshu.com/p/b5e340ec9551

Example program for the proxy model

We'll implement a printer that prints a string to the screen, and then hand off to a proxy object to do that.

First, look at the class diagram.

image.png

Printer category.

package Proxy;

public class Printer implements Printable {
    private String name;
    public Printer() {
        heavyJob("Being generatedPrinter examples of");
    }
     public Printer(String name) { // constructor
        this.name = name;
        heavyJob("Being generatedPrinter examples of(" + name + ")");
    }
     public void setPrinterName(String name) { // Set the name
        this.name = name;
    }
     public String getPrinterName() { // Get the name
        return name;
    }
     public void print(String string) { // Display the text with the printer name
        System.out.println("=== " + name + " ===");
        System.out.println(string);
    }
     private void heavyJob(String msg) { // re-live
        System.out.print(msg);
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.print(".");
        }
        System.out.println(" close。");
    }
}

Printable interface.

package Proxy;

public interface Printable {
    public abstract void setPrinterName(String name);
    
    public abstract String getPrinterName();
    
    public abstract void print(String string); 
}

PrinterProxy class, using the reflection mechanism, dynamically generates the object being proxied and delays initialization until it needs to be invoked

package Proxy;

public class PrinterProxy implements Printable {
     private String name;             // Name
private Printable real;          // "I"                 
     private String className;        // Class name for "me"       
     public PrinterProxy(String name, String className) { // constructor     
        this.name = name;
        this.className = className;                                                 
    }
     public synchronized void setPrinterName(String name) { // Set the name
        if (real != null) {
             real.setPrinterName(name);   // Also set the name of "me"
        }
        this.name = name;
    }
     public String getPrinterName() { // Get the name
        return name;
    }
     public void print(String string) { // Display
        realize();
        real.print(string);
    }
     private synchronized void realize() { // Generate "myself"
        if (real == null) {
            try {                                                                       
                real = (Printable)Class.forName(className).newInstance();               
                real.setPrinterName(name);                                              
            } catch (ClassNotFoundException e) {                                        
                System.err.println(" Not found " + className + "  kind。");      
            } catch (Exception e) {                                                     
                e.printStackTrace();                                                    
            }                                                                           
        }
    }
}

Main Class Test.

package Proxy;

public class Main {
    public static void main(String[] args) {
        Printable p = new PrinterProxy("Alice", "Proxy.Printer");                 
        System.out.println(" Now the name is" + p.getPrinterName() + "。");
        p.setPrinterName("Bob");
        System.out.println(" Now the name is" + p.getPrinterName() + "。");
        p.print("Hello, world.");
    }
}

Results of the run.

image.png

Analysis of the agency model

Roles in the proxy model.

  • Subject The Subject role defines the interface that gives consistency between the proxy and realsubject roles. This interface provides the advantage that the client does not have to distinguish whether it is using a proxy object or a real object. Corresponding to the Printable role in the instance
  • Proxy (agent) The Proxy role will try to handle requests from the Client role. Only when you can't handle it yourself, give the job to the real object. Proxy objects are only generated as real objects when necessary. The instance corresponds to a PrinterProxy object.
  • RealSubject (real object) is the object that actually does the work, corresponding to the Printer object in the example.

Class diagram of the proxy model.

image.png

  • Using proxies to boost speed The key lies in delayed initialization. We can wait until we need to use the function of the real object before initializing it. This has the advantage of improving performance. You may not see this advantage from our example, suppose we have a large system, if we all initialize all functions and initialize all instances when the system starts, then obviously the system will become very slow to start. But if we use the proxy pattern, then we will initialize the object when we have to. This speeds up the system startup.
  • Representation and delegation In fact, with all the design patterns we've learned, doesn't it feel like delegation is simply everywhere. Almost every design pattern uses delegates, and it's no surprise that the proxy pattern is a proxy for objects delegating real objects. Because delegates can be objects that relate to each other and call each other. So delegation is present in many design patterns.

Recommended>>
1、Thats how yesterdays malicious email came about
2、UZI has quickly risen to the top of the major stats charts since his return Once again dominating the charts proves strength
3、Magic stickers can fool computer vision software AI systems still have to get over this hurdle
4、Uber opensources neural evolution visualization tool VINE
5、Extraordinary Hu Blockchain which is redefining the world

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号