Design Mode Study Notes-Proxy Mode

Source: Internet
Author: User


Before model learning


What is the design model: when we design the program, we gradually formed some typical problems and solutions, which is the software model; each mode describes a problem that often occurs in our program design and the solution to the problem. When we encounter the problem described by the mode, the corresponding solution can be used to solve the problem. This is the design mode.

A design pattern is an abstract thing. It is not learned but used. Maybe you don't know any pattern at all, and you don't consider any pattern, but write the best code, even from the perspective of "pattern experts", they are all the best designs and have to say "best pattern practices". This is because you have accumulated a lot of practical experience, knowing "where to write code" is a design pattern.

Some people say: "If the level is not reached, you can learn it in vain. If the level is reached, you can do it yourself ". It is true that the mode is well-developed and may still not be able to write good code, let alone design a good framework. OOP understanding and practical experience reach a certain level, and it also means to summarize a lot of good design experience, however, it may not be the case that "no teacher can do anything", or you can say that, on the basis of level and experience, it is time for the system to learn the "mode, it is helpful to learn the experts' summary and verify your own shortcomings.

This series of design patterns learning notes is actually a Learning Record for the book "Java and patterns.


Definition of proxy Mode


The proxy mode provides a proxy object for an object and controls the reference to the original object by the proxy object.

Proxy mode is called Proxy or Surrogate in English and can be translated into "Proxy" in Chinese ". The so-called proxy means one person or one institution takes action on behalf of another person or another institution. In some cases, a client does not want or cannot directly reference an object, and the proxy object can play a mediation role between the client and the target object.

The difference between the proxy mode and the adapter mode: the adapter mode is intended to change the interfaces of the objects to be considered, while the proxy mode cannot change the interfaces of the objects to be proxy.

The difference between the proxy mode and the decoration mode: The decoration mode should provide enhanced functions for the decorated objects, while the proxy mode does not provide enhanced functions for the objects.

Code mode and facade mode: Sometimes the facade mode serves as the proxy. At this time, the facade mode is also called the proxy facade mode or the facade proxy mode.


Proxy mode structure


Class Diagram and sequence diagram

Release/release/zo7u0 + release + DNrLXEvdO/2qOs0tSx47/release/ydLUzOa0 + release/OjqLrNyb6z/release + release/release + LK7yse1pbS/release + release/release cjwvcD4KPGgyPrT6wuvKtc/WPC9oMj4KPHA + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java; "> abstract class Subject {public abstract void request ();} class RealSubject extends Subject {public RealSubject () {} public void request () {System. out. println ("From real subject") ;}} class ProxySubject extends Subject {private RealSubject realSubject; public ProxySubject () {} public void request () {preRequest (); if (realSubject = null) {realSubject = new RealSubject ();} realSubject. request (); postRequest () ;}// the private void preRequest () operation before the request () {// something you want to do before requesting} // private void postRequest () {// something you want to do after requesting }}

JDK support for proxy Mode


Since JDK3, reflection class libraries are provided to create proxy objects at runtime. The following example describes how to use java. lang. reflect. Proxy. First, this example provides a proxy object for the Vector object. When any method of the Vector is called and called, two pieces of information are printed respectively, this indicates that the proxy object has the ability to intercept and control the Vector object.


Structure chart



Code Implementation

Import java. lang. reflect. invocationHandler; import java. lang. reflect. proxy; import java. lang. reflect. method; import java. util. *; class VectorProxy implements InvocationHandler {private Object proxyobj; public VectorProxy (Object obj) {this. proxyobj = obj;} public static Object factory (Object obj) {Class cls = obj. getClass (); return Proxy. newProxyInstance (cls. getClassLoader (), cls. getInterfaces (), new VectorProx Y (obj);} public Object invoke (Object proxy, Method method, Object [] args) throws Exception {System. out. println ("before calling" + method); if (args! = Null) {for (int I = 0; I

Proxy type


Depending on the purpose of use, there are several proxies: Remote proxy, Virtual proxy, Copy-on-Write proxy, protection (Protect or Access) proxy, Cache proxy, Firewall proxy, Synchronization proxy, Smart Reference proxy.

There are four common types:

(1) remote proxy: proxy for remote access, which has the advantage of hiding network details and allowing remote access like accessing local objects; the disadvantage is that the customer may not realize that it will start a time-consuming remote call, so there may be no necessary mental preparation.

(2) protection proxy: You can check the permissions at runtime and pass the call to the proxy object after verification.

(3) intelligent reference Proxy: Performs Housekeeping operations, such as counting operations, when accessing an object.

(4) virtual Proxy: the advantage of using the virtual proxy mode is that the proxy object can be loaded only when necessary. Delayed loading mode.


Protection proxy and smart reference proxy Cases


Class Diagram and sequence diagram


Code Implementation

Class Client {private static Searcher searcher; public static void main (String [] args) {searcher = new Proxy (); String userId = "Admin"; String searchType = "SEARCH_BY_ACCOUNT "; string result = searcher. doSearch (userId, searchType); System. out. println (result) ;}} interface Searcher {String doSearch (String userId, String searchType);} class Proxy implements Searcher {private RealSearcher searcher; private UsageLogger usageLogger; private AccessValidator accessValidator; public Proxy () {searcher = new RealSearcher () ;}// query public String doSearch (String userId, String keyValue) {if (checkAccess (userId )) {String result = searcher. doSearch (null, keyValue); logUsage (userId); return result;} else {return null ;}// the authorized operation before the query is private boolean checkAccess (String userId) {accessValidator = new AccessValidator (); return accessValidator. validateUser (userId);} // The queried log operation private void logUsage (String userId) {UsageLogger logger = new UsageLogger (); logger. setUserId (userId); logger. save () ;}} class RealSearcher implements Searcher {public RealSearcher () {}// real query public String doSearch (String userId, String keyValue) {return "Real query result" ;}} class AccessValidator {// permission query of the user occurs here: public boolean validateUser (String userId) {if (userId. equals ("Admin") {return true;} else {return false ;}} class UsageLogger {private String userId; public void setUserId (String userId) {this. userId = userId;} // log public void save (){//...} public void save (String userId) {this. userId = userId; save ();}}


Learn more


There are many application scenarios in the daily development process about the proxy mode. For example, when WebService is called, the agent class of the client is automatically or manually generated. This is the remote proxy mode. For Logon, the protection proxy and intelligent reference proxy can always be used.

For protection proxy and intelligent reference proxy, we may often merge the proxy topic role and the actual topic role in the past. We can try to split the proxy according to the responsibilities in the proxy mode.


Structure Pattern Summary


There are seven schema patterns: adapter, decoration, synthesis, proxy, metadata, facade, and bridge.

Summary:


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.