ArticleDirectory
The proxy mode is described as follows in Dr. Yan Hong's book Java and patterns:
The proxy mode is the structure mode of the object. The proxy mode provides a proxy object for an object and controls the reference to the original object by the proxy object.
Proxy mode structure
A proxy means that one person or institution takes action on behalf of another person or 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 proxy mode class diagram is as follows:
Role in proxy mode:
●Abstract object role:Declares the common interfaces of the target object and the proxy object, so that the proxy object can be used wherever the target object can be used.
●Target object role:Defines the target object represented by the proxy object.
●Proxy object role:The proxy object contains references of the target object, so that the target object can be operated at any time. The proxy object provides the same interface as the target object, so that the target object can be replaced at any time. A proxy Object usually performs an operation before or after the client call is passed to the target object, instead of simply passing the call to the target object.
Source code
Abstract object role
Public Abstract ClassAbstractobject {//OperationPublic Abstract VoidOperation ();}
Target object role
Public ClassRealobjectExtendsAbstractobject {@ overridePublic VoidOperation (){//Some operationsSystem. Out. println ("some operations");}}
Proxy object role
Public ClassProxyobjectExtendsAbstractobject {realobject=NewRealobject (); @ overridePublic VoidOperation (){//You can perform related operations before calling the target object.System. Out. println ("before"); Realobject. Operation ();//Related operations can be performed after the target object is called.System. Out. println ("after");}}
Client
Public ClassClient {Public Static VoidMain (string [] ARGs ){//Todo auto-generated method stubAbstractobject OBJ =NewProxyobject (); obj. Operation ();}}
From the above example, we can see that the proxy object delegates the client call to the target object, and can perform specific operations before and after the method of the target object is called.