C # design mode 13 Agent mode (proxy) "Structural type"

Source: Internet
Author: User

First, Introduction

Today we are going to talk about the "structural" design pattern of the seventh mode, is also the "structural" design pattern of the last mode, the mode is "proxy mode", the English name is: Proxy pattern. Or the old routine, first look at the name. "Agent" can be understood as "replace", instead of "master" to do something, why the need for "agent", because of some reasons (such as security reasons), do not want to "master" directly face these cumbersome, complex problems, but these things are "master" agreed or inspired, as "master" Done in person. This pattern is simple and there are many examples of life. For example, the singer, movie star's agent is a real-life proxy model of a good example, there is a firewall in the operating system, is also an example of the agent, to access the system, first through the firewall this, otherwise avoid talking. There are many, do not list, everyone in life slowly experience it.

second, the agent model of the detailed introduction

2.1. Motive (motivate)

In an object-oriented system, some objects, for some reason (such as the overhead of object creation, or the need for security control of some operations, or the need for out-of-process access), can cause a lot of trouble for the user, or the system structure. How do you manage/control the complexity inherent in these objects without losing the transparent operands? Adding a layer of indirect layer is a common solution in software development.

2.2. Intention (Intent)

Provides a proxy for other objects to control access to this object. --"Design pattern" GoF

2.3. Structure Diagram



2.4, the composition of the model

There are three roles involved in the proxy mode:

(1), abstract theme Role (Subject): A public interface that declares a real topic and a proxy theme, so that you can use a proxy theme anywhere you use a real theme.

(2), Agent theme Role (proxy): The agent theme role contains a reference to the real topic, so that you can manipulate the real subject object; The agent-themed role is responsible for creating real-world theme objects when needed; agent roles typically perform some other action before or after a client call is passed to a real topic , rather than simply passing the call to a real-world theme object.

(3), real theme Role (Realsubject): Defines the real object represented by the proxy role.

Attached: During the development of WCF or webservice, when we add a service reference to the client, we add some extra classes in the customer program, and the client-generated class acts as the agent-themed role, and our clients directly invoke these proxy roles to access the operations provided by the remote service. This is a typical example of a remote agent.

2.5, the classification of proxy mode:

The proxy mode can be divided into the following categories according to the purpose of use:

(1) Remote proxy: Provides a local representative object for an object that is located in a different address space. This can be a different address space in this computer, or in another computer. The most typical example is a client invoking a Web service or a WCF service.

(2) Virtual proxy: Create a resource-intensive object as needed so that the object is actually created only when it is needed.

(3), copy-on-write Agent: One kind of virtual agent, the replication (or clone) delay until only when the client needs, really take action.

(4), protection (Protect or access) Proxy: Control access to an object, you can give different users different levels of use rights.

(5), Firewall (Firewall) Agent: Protect the target not to let malicious users close.

(6), smart Reference (Smart Reference) Proxy: When an object is referenced, it provides some extra action, such as logging the number of calls to this object.

(7), Cache Agent: Provides temporary storage space for the results of a target operation so that multiple clients can make these results.

In all kinds of proxy modes above, virtual agents, remote agents, smart reference agents, and protection agents are the most common proxy modes.

2.6, the specific implementation of the agent mode

Speaking of "proxy mode", in fact, it is very easy, real life examples are also many. Star brokers, the country's spokesmen are good examples of proxies. We will use the Star Agent this thing to introduce the "proxy mode" implementation of it.

1   2 namespaceimplementation of proxy mode3 {4     /// <summary>5     ///big stars are rich, rich, you can ask their own brokers, with a broker, a lot of things do not have their own pro-force. Get some gossip, speculation through the broker can be justified by the operation of, in case of bad, oneself can also deny. 6     /// </summary>7     classClient8     {9         Static voidMain (string[] args)Ten         { One             //recently, fan name star attention to a bit of decline, to dot speculation AAgentabstract fan=NewAgentperson (); - fan. Speculation (); -  the             //after a period of time, and not, and then hype again - fan. Speculation (); -  -  + Console.read (); -         } +     } A   at  -     //This type is an abstract subject role that defines the interface methods common to the role of the agent and the real principal role. -      Public Abstract classagentabstract -     { -  -         //This method performs a specific hype---the method is equivalent to the request method of abstract subject in          Public Abstract voidspeculation (); -     } to   +     //the type is fan name star, rich and powerful, want to fry what to fry what---equivalent to the specific realsubject role -      Public Sealed classfanstar:agentabstract the     { *         //Rich and powerful, background. $          PublicFanstar () {}Panax Notoginseng  -         //to have fame, to hype regularly---is the realsubject type of request method the          Public Override voidspeculation () +         { AConsole.WriteLine ("I'm going to hype up."); the         } +     } -   $     //the type is the proxy type----equivalent to the specific proxy role $      Public Sealed classagentperson:agentabstract -     { -         //This is the boss behind it, the         PrivateFanstar boss; - Wuyi         //The boss is behind the orders . the          PublicAgentperson () -         { Wuboss=NewFanstar (); -         } About  $         //The method of speculation, the implementation of specific speculation---is the type of Proxy request method -          Public Override voidspeculation () -         { -Console.WriteLine ("get some gossip, shoot some wild photos ."); ABoss. Speculation ("occasionally come out and show up for hype"); +Console.WriteLine ("and then the press conference, the sad Cry, keep on"); the         } -     } $}


This pattern is very simple, it is not much to talk about.

Three, the implementation of the agent model points:

"Adding a layer of indirect layer" is a common solution to many complex problems in software system. In object-oriented system, the direct use of some objects will bring many problems, as the proxy object of the indirect layer is a common means to solve this problem. The implementation of the specific proxy design mode, the granularity of the implementation of a large difference, some may be a single object to do fine-grained control, such as Copy-on-write technology, some may provide the component module with an abstract proxy layer, at the level of the structure of the object proxy.

Proxy does not necessarily require maintaining the consistency of the interface, as long as the indirect control can be achieved, sometimes the loss of some transparency is acceptable.

Advantages:

The proxy mode can be used to isolate the calling object, and to some extent, the coupling degree of the system is reduced;

The proxy object acts as a mediator between the client and the target object, which can be used to protect the target object. The proxy object can perform an additional operation, such as permission checking, before making a request to the target object.

Disadvantages:

Because a proxy object is added between the client and the real topic, the processing speed of the request becomes slower

Implementing the proxy class also requires additional work, which increases the complexity of the system's implementation.


Iv. Implementation of proxy patterns in. NET

There are also many implementations of the proxy mode in the net FCL, at the framework level, and at the class level. With wcf,remoting at the framework level, they all need to generate local proxies and then access objects outside the process or outside the machine through proxies. Class-level has StringBuilder type, StringBuilder is actually a kind of proxy, we mean to access the string, StringBuilder is a variable string proxy, Also, StringBuilder does not maintain interface consistency with string.

v. Summary

As of today, we have finished two parts of the three parts of our design pattern, the first part is the design pattern of "creation", solving the problem of object creation and decoupling the creation of objects. The second part is the "structure" of the design pattern, the so-called structural design pattern pattern, as the name implies is the structure of classes and objects, mainly used to deal with the combination of classes or objects. It includes two types, one is the class structure pattern, refers to the use of inheritance mechanism to combine the interface or implementation, and the other is the object structure pattern, refers to the method of combining objects to achieve new functions. It includes adapter mode, bridging mode, adorner mode, combined mode, appearance mode, and the enjoy meta mode and proxy mode. Design mode to now also said a lot of, but looks like a lot of patterns are very similar, between seems to be very tolerant of conversion, sometimes the conditions are different, indeed patterns can be converted, but not wanton conversion. In order to avoid the confusion of thought, we put the "structure" of the design patterns, summed up once again, grasp the core, understand the use of the scene.

Adapter mode focuses on the conversion interface, matching interfaces that do not match the docking

Bridging mode focuses on the separation of interfaces and their implementation, supporting multi-dimensional changes

The combination mode focuses on the unified interface, the "one-to-many" relationship into a "one-to-one" relationship

Decorator mode focuses on stabilizing the interface, in this case extending the function to the object

The appearance mode focuses on simplifying the interface, simplifying the dependencies between the component system and the external client program

The enjoy meta-mode focuses on preserving interfaces and optimizes object storage using shared technology internally

The agent mode focuses on the borrowing interface and adds the indirect layer to achieve flexible control.

Starting with the next article, "Behavioral" design patterns, this is the end of today.

C # design mode 13 Agent mode (proxy) "Structural type"

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.