Original: C # design mode 12 proxy pattern "structural type"
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 (Structure)
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-themed role (proxy): The proxy theme role contains a reference to a real topic, which allows you to manipulate real-world subject matter, and the agent-themed role is responsible for creating a real-world theme object when needed; A proxy role typically performs some other action before or after a client call is passed to a real topic. Instead of simply passing the call to the real subject object.
(3), real theme Role (Realsubject): Defines the real object that the proxy role represents.
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 namespaceimplementation of proxy mode2 {3 /// <summary>4 ///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. 5 /// </summary>6 classClient7 {8 Static voidMain (string[] args)9 {Ten //recently, fan name star attention to a bit of decline, to dot speculation OneAgentabstract fan =NewAgentperson (); AFan. Speculation ("occasionally come out and show up for hype"); - - Console.WriteLine (); the - //after a period of time, and not, and then hype again -Fan. Speculation ("this time is not fire, began to divorce 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 - { - in //This method performs a specific hype---the method is equivalent to the request method of abstract subject - Public Virtual voidSpeculation (stringthing) to { + Console.WriteLine (thing); - } the } * $ //the type is fan name star, rich and powerful, want to fry what to fry what---equivalent to the specific realsubject rolePanax Notoginseng Public Sealed classfanstar:agentabstract - { the //Rich and powerful, background. + PublicFanstar () {} A the //to have fame, to hype regularly---is the realsubject type of request method + Public Override voidSpeculation (stringthing) - { $ Console.WriteLine (thing); $ } - } - the //the type is the proxy type----equivalent to the specific proxy role - Public Sealed classagentperson:agentabstractWuyi { the //This is the boss behind it, - PrivateFanstar boss; Wu - //The boss is behind the orders . About PublicAgentperson () $ { -Boss =NewFanstar (); - } - A //The method of speculation, the implementation of specific speculation---is the type of Proxy request method + Public Override voidSpeculation (stringthing) the { -Console.WriteLine ("get some gossip, shoot some wild photos ."); $ Base. Speculation (thing); theConsole.WriteLine ("and then the press conference, the sad Cry, keep on"); the } the } 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.
3.1 ", the advantages of Agent mode:
(1), the proxy mode can be used to isolate the calling object, and to some extent, the coupling degree of the system is reduced;
(2), the proxy object acts as an intermediary 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.
different types of proxy modes also have unique advantages, such as:
(1),Remote AgentProvides an implementation mechanism for access to two different address space objects and can move objects and operations that consume more resources to a better-performing computer to improve the overall efficiency of the system.
(2),Virtual AgentBy using an object that consumes less resources to represent an object that consumes more resources, it can save the operating overhead of the system to some extent.
(3),buffering AgentProvides temporary cache storage for the results of an operation so that these results can be shared in subsequent use, optimizing system performance and reducing execution time.
(4),Protection AgentYou can control access to an object and provide different levels of usage rights for different users.
3.2 ", the disadvantage of proxy mode:
(1), because a proxy object is added between the client and the real topic, the processing speed of the request is slow
(2), the implementation of the proxy class also requires additional work, thereby increasing the complexity of the system implementation.
3.3 ", Proxy mode usage scenario:
There are many types of proxy modes, and different types of proxy modes have different advantages and disadvantages, and they are applied to different situations:
(1) When the client object needs to access objects in the remote host, you can use theRemote Agent。
(2), when it is necessary to use a less resource-consuming object to represent a more resource-intensive object, thereby reducing the system overhead, shorten the running time can be usedVirtual Agent, such as when an object takes a long time to finish loading.
(3) When it is necessary to provide a temporary storage space for one of the frequently accessed operation results, which can be used by multiple clients to share access to these resultsbuffering Agent。 By using a buffer proxy, the system does not have to re-perform the operation every time the client accesses, just get the result of the operation directly from the temporary buffer.
(4), when you need to control access to an object, to provide different levels of access to different users can useProtection Agent。
(5) When you need to provide some extra action for an object's access (reference), you can use theSmart Reference Agent。
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 12 proxy pattern "structural type"