Proxy pattern _ supplement

Source: Internet
Author: User

Preface:

The internal principle, role, and implementation of the proxy mode are explained in detail in the previous blog. This article only supplements its content and introduces other proxies.

1. Virtual proxy

First, define the role of the virtual Proxy: Use a virtual proxy to replace a large object before a large object is created. (This ensures that a large object is created only when necessary, avoid resource waste)

We may often use virtual proxy, but we don't know it, for example:

In our program, operations that consume resources such as intensive computing or getting a large amount of data from the server usually display the default information first, or an animation indicates that our program is still working hard and the obtained information is displayed after the operation is completed.

The idea of virtual proxy is used, but the virtual proxy separates all the work waiting for the operation to be completed and encapsulates it into a virtual proxy object, directly interacting with customers is a virtual proxy rather than the objects that actually do things.

After receiving a request from the customer, the virtual proxy has done the following:

  1. If the actual object does not exist (not created or not created yet), the customer request is recorded and the default information is displayed. After the actual object is created, the request is passed to the actual object.
  2. If the actual object already exists, the customer request is directly delegated to the actual object.
  3. The proxy object is responsible for displaying the default information (or performing the default processing) before the actual object does not return the operation result)
  4. Pass the operation result directly to the customer (yes, the proxy task is "Submit" and "accept ")

Since it is a proxy, it is necessary to pretend to be an actual object, so the customer cannot discover the existence of the proxy, so the class diagram of the virtual proxy is as follows:

The client holds a virtual proxy object proxy, and the proxy holds a specific service object myservice

More importantly, the virtual proxy and the specific service myservice both expand from the service interface, so the proxy and the actual object have the same behavior, the customer will not find the existence of the proxy

Ii. Proxy Protection

Protect agents from playing the role of a broker. (Not everyone can contact the stars behind me. You can only contact me. You will be transferred only after I confirm that you are not a bad person ..)

In other words, the protection proxy provides access control for the actual object, ensuring that only valid callers can get the service.

The class diagram is exactly the same as the above virtual proxy, but the proxy has an additional responsibility for judging the caller's permissions (what have you found? We seem to be able to combine multiple proxies. Of course, such proxies no longer meet the single responsibility principle of the class, but it doesn't matter, we can create a proxy to manage a series of proxies ..)

In fact, Java APIs provide support for the proxy mode (Dynamic proxy)

The dynamic proxy provided by Java is embodied in the proxy class (yes, it is a class, not an object) that is created at runtime. We cannot directly modify the internal implementation of proxy, but we can use invocationhandler to tell proxy how to do it.

The basic idea of using dynamic proxy to protect proxy is to create multiple proxies. Different proxies indicate the services corresponding to callers with different permissions.

Let's design a scenario and try to use dynamic proxy to implement proxy protection:

Blog thumb ups: You can likes others' blog posts, but you cannot likes your own blog posts. However, both bloggers and visitors can see the number of likes.

The scenario is relatively simple, but it is enough to explain the problem. The following describes how to simulate the implementation.

-------

First, you must have bloguser:

Package proxypattern. protectionproxy;/*** defines the blog User Interface * @ author ayqy */public interface bloguser {public void support (); Public int getsupportcount ();}

Concreteuser is also required, and its implementation process is relatively simple.

The following describes how to create a dynamic proxy. There are two types of permissions: bloggers and visitors. Therefore, we need at least two different dynamic proxies.

Authorhandler:

Package proxypattern. protectionproxy; import Java. lang. reflect. invocationhandler; import Java. lang. reflect. invocationtargetexception; import Java. lang. reflect. method;/*** implement invocationhandler * @ author ayqy */public class authorhandler implements invocationhandler {bloguser user; Public authorhandler (bloguser user) {This. user = user ;}@ overridepublic object invoke (Object proxy, method, object [] ARGs) throws illegalaccessexception {// declares an invalid access exception. Try {/* If the blogger wants to view the number of likes, delegate the user to the caller for specific operations */If (method. getname (). equals ("getsupportcount") {return method. invoke (user, argS);}/* if you like it, an exception is thrown, indicating that the request is rejected */If (method. getname (). equals ("support") {Throw new illegalaccessexception () ;}} catch (invocationtargetexception e) {// todo auto-generated catch blocke. printstacktrace ();} return NULL; // if other methods are called, ignore them }}

Similarly, you also need to implement visitorhandler

With multiple proxies, we also need to implement the proxy, that is, to protect the proxy (depending on the caller's permission, a corresponding dynamic proxy is returned)

Protectionproxy:

Package proxypattern. protectionproxy; import Java. lang. reflect. proxy; /*** implement protection proxy * @ author ayqy */public class protectionproxy {/*** @ Param user caller * @ return proxy */Public bloguser getauthorproxy (bloguser user) {return (bloguser) proxy. newproxyinstance (user. getclass (). getclassloader (), user. getclass (). getinterfaces (), new authorhandler (User);}/*** @ Param user caller * @ return visitor's proxy */Public bloguser getvisitorproxy (bloguser user) {return (bloguser) proxy. newproxyinstance (user. getclass (). getclassloader (), user. getclass (). getinterfaces (), new visitorhandler (User);}/* Insert the method for generating other proxies here */}

With these, it is enough to do a simple test:

Package proxypattern. protectionproxy;/*** implementation test class * @ author ayqy */public class test {public static void main (string [] ARGs) {// create protection proxy protectionproxy = new protectionproxy (); system. out. println ("master part:"); // create the proxy bloguser authorproxy = proxy for the master. getauthorproxy (New concreteuser (); system. out. println ("Main blog views total number of likes"); system. out. println ("liked" + authorproxy. getsupportcount () + ""); // you can give yourself a thumbs up on the system. out. println ("blog thumb ups"); try {authorproxy. support ();} catch (exception e) {system. out. println ("thumbs up failed, you cannot like yourself");} system. out. println ("like, liked" + authorproxy. getsupportcount () + "times"); system. out. println ("\ n visitor part:"); // create the proxy bloguser vistorproxy = proxy for the visitor. getvisitorproxy (New concreteuser (); system. out. println ("visitors want to view the total number of likes"); system. out. println ("liked" + vistorproxy. getsupportcount () + ""); // you can give yourself a thumbs up on the system. out. println ("visitors want to give the bloggers a thumbs up"); try {vistorproxy. support ();} catch (exception e) {system. out. println ("thumb up failed, unknown reason");} system. out. println ("liked, liked" + vistorproxy. getsupportcount () + "times ");}}

Test results:

3. Other proxies

The proxy mode is widely used and cannot list all proxies one by one. Here we will briefly introduce several common proxies:

Proxy name Function
Firewall proxy Control access to network resources and protect 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, and allows multiple customers to share the results to reduce computing or network latency.
Synchronization proxy Provides secure access to topics with multiple threads
Complex hidden proxy (appearance proxy) Used to hide the complexity of a complex set of classes and perform access control (more powerful than the appearance Mode)
Copy proxy during write Used to control the replication of objects by delaying the replication of objects until the real replication is required (similar to the virtual proxy)

Of course, as long as you understand the original remote proxy, it is easy to understand these proxies ..

Proxy pattern _ supplement

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.