Proxy mode: Proxy from aliang. NET)

Source: Internet
Author: User
Proxy mode provides a Proxy for an object, and the Proxy object controls the reference to the original 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.

Ii. Types of proxies

If the proxy is divided by purpose, there are the following types of proxies:

Remote Proxy: provides a Local Area Representative object for an object in a different address space. This address space can be in this machine, but also in another machine. Remote proxy is also called Ambassador ).
Virtual Proxy: creates an object with high resource consumption as needed, so that the object is created only when necessary.
Copy-on-Write Proxy: a virtual proxy. The replication (clone) operation is performed only when the client needs it.
Protection (Protect or Access) proxy: controls Access to an object. If necessary, different users can be granted different levels of Access permissions.
Cache Proxy: provides a temporary storage space for the results of a target operation so that multiple clients can share the results.
Firewall Proxy: protects the target from malicious users.
Synchronization Proxy: enables several users to simultaneously use an object without conflict.
Smart Reference Proxy: provides some additional operations when an object is referenced, such as recording the number of calls to this object.
In all types of Proxy modes, Virtual Proxy, Remote Proxy, Smart Reference Proxy, and Protect or Access) proxy is the most common proxy mode.

Iii. Example of remote proxy

Achilles is a tool software used to test the security performance of a website. Achilles is equivalent to a desktop proxy server located on the client. It acts as a intermediary in an HTTP Process, but Achilles is different from the usual proxy server. Achilles intercepts two-way communication data, allowing Achilles software users to change data from and to network servers, or even intercept and modify SSL communication. (This is not clearly explained in Java and pattern. Regarding anti-asymmetric key encryption interception and cracking methods, refer to my other article "intercept and modify asymmetric key encryption information through proxy").

Another example is Windows shortcuts. A shortcut is a proxy of the program it references.

Iv. Proxy mode structure

Shows the class diagram of the proxy mode:

The proxy mode involves the following roles:

Abstract topic role (Subject): Declares the common interface between a real topic and a proxy topic, so that a proxy topic can be used wherever a real topic is used.

Proxy topic role: the Proxy topic role contains references to the real topic, so that you can operate on the real topic object at any time; the proxy topic role provides the same interface as the real topic role to replace the real subject at any time. It controls the application of the real topic, creates real theme objects (and deletes real theme objects) as needed. A proxy role usually performs an operation before or after passing client calls to a real theme, instead of simply passing the call to a real theme object.

RealSubject role: defines the real objects represented by the proxy role.

V. Proxy mode DEMO code

The following sample code implements the proxy mode:

// Proxy pattern -- Structural example  using System;// "Subject"abstract class Subject{  // Methods  abstract public void Request();}// "RealSubject"class RealSubject : Subject{  // Methods  override public void Request()  {    Console.WriteLine("Called RealSubject.Request()");  }}// "Proxy"class Proxy : Subject{  // Fields  RealSubject realSubject;  // Methods  override public void Request()  {    // Uses "lazy initialization"    if( realSubject == null )      realSubject = new RealSubject();    preRequest();    realSubject.Request();    postRequest();  }  public void preRequest()  { Console.WriteLine("PreRequest."); }  public void postRequest()  { Console.WriteLine("PostRequest."); }}/**//// <summary>/// Client test/// </summary>public class Client{  public static void Main( string[] args )  {    // Create proxy and request a service    Proxy p = new Proxy();    p.Request();  }}

6. Gao laozhuang Wukong

Although the eight precepts were not called at that time, they were still called here for convenience.

Story of Gao laozhuang

However, during the Spring Festival, Wukong took a white horse and traveled west with Tang Miao. One day later, the sky will be late, far from seeing a village people, this is Gao Lao Zhuang, pig Ba Jie's man Gao Taigong's home. In order to save Miss Gao's three masters, Wukong decided to dress up as Miss Gao, and later met the Monster:

"The Walker turned to the magic and changed his body, just like the woman. She sat alone in the room and waited for the goblin. In a few moments, there is a storm of wind ...... When the storm passed, I saw a fairy in the air, and it was really ugly: black face, short hair, long-beam ears, wearing a green, blue, blue, no blue shuttle straight, fasten a cloth towel ...... When you walk into the room, you have to put your eyes on it ...... "

The appearance of Miss Gao's three gods and herself

Wu kong's start is to separate the God appearance of Miss Gao's three masters from her, which is similar to the principle of "Opening and Closing. In this way, "Miss Gao jia" becomes the specific implementation of "Miss Gao Jia San Shen appearance", and "Miss Gao Jia San Shen appearance" becomes an abstract role, as shown in.

Wukong assumes and replaces Miss Gao's three roles

Wukong cleverly realized "the appearance of Miss Gao's three gods", that is, it also became a subclass of "the appearance of Miss Gao's three gods. Wukong can assume the role of Miss Gao's three roles and replace Miss Gao's three roles with Miss Ba Jie. Its static structure is shown in.

Wukong replaces "Miss Gao's three masters" to meet with pig. Obviously, this is the application of proxy mode. Specifically, this is an application that protects the proxy mode. Client requests are sent to the real theme object only when the proxy object is considered appropriate.

Bajie cannot tell true and false wife

From the description of Journey to the West, we can see that pig cannot identify the "Miss Gao jia" and "Miss Gao jia" played by Wukong ". The client cannot identify the proxy topic object and the real topic object. This is a proxy mode.
Important purpose.

Figure 5 shows the object map of Miss gokuai in place of Miss gokuai.


7. Different types of proxy Modes

Remote proxy

The network details can be hidden so that the client does not have to consider the existence of the network. The customer can think that the objects to be proxy are local rather than remote, and the proxy objects undertake most of the network communication work, as shown in the remote proxy structure.

Virtual proxy

The advantage of using the virtual proxy mode is that the proxy object can be loaded only when necessary. The agent can optimize the loading process as necessary. When loading a module is very resource-consuming, the advantages of virtual proxy are very obvious.

Protection proxy

The protection proxy can check the relevant permissions of the user during the running time, and then decide to pass the call to the object to be proxy after verification.

Intelligent reference proxy

When accessing an object, you can perform Housekeeping operations, such as counting operations.

8. Example of proxy Mode Application

This example demonstrates the use of remote proxy mode to provide access control for objects in another application domain (AppDomain.

// Proxy pattern -- Real World exampleusing System;using System.Runtime.Remoting;// "Subject" public interface IMath{  // Methods  double Add( double x, double y );  double Sub( double x, double y );  double Mul( double x, double y );  double Div( double x, double y );}// "RealSubject" class Math : MarshalByRefObject, IMath{  // Methods  public double Add( double x, double y ){ return x + y; }  public double Sub( double x, double y ){ return x - y; }  public double Mul( double x, double y ){ return x * y; }  public double Div( double x, double y ){ return x / y; }}// Remote "Proxy Object" class MathProxy : IMath{  // Fields  Math math;  // Constructors  public MathProxy()  {    // Create Math instance in a different AppDomain    AppDomain ad = System.AppDomain.CreateDomain("MathDomain",null, null );    ObjectHandle o = ad.CreateInstance("Proxy_RealWorld", "Math", false,      System.Reflection.BindingFlags.CreateInstance, null, null, null,null,null );    math = (Math) o.Unwrap();  }  // Methods  public double Add( double x, double y )  {     return math.Add(x,y);   }  public double Sub( double x, double y )  {     return math.Sub(x,y);   }  public double Mul( double x, double y )  {     return math.Mul(x,y);   }  public double Div( double x, double y )  {     return math.Div(x,y);   }}/**//// <summary>///   ProxyApp test/// </summary>public class ProxyApp{  public static void Main( string[] args )  {    // Create math proxy    MathProxy p = new MathProxy();    // Do the math    Console.WriteLine( "4 + 2 = {0}", p.Add( 4, 2 ) );    Console.WriteLine( "4 - 2 = {0}", p.Sub( 4, 2 ) );    Console.WriteLine( "4 * 2 = {0}", p.Mul( 4, 2 ) );    Console.WriteLine( "4 / 2 = {0}", p.Div( 4, 2 ) );  }}

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.