The Proxy mode is also one of the most common design patterns. Reflection applications in java and. net and a large number of open-source frameworks are used repeatedly. Key recommendations.
Overview
Provides a proxy for other objects to control access to this object.
Applicability
1. RemoteProxy provides a local representation of an object in different address spaces.
2. VirtualProxy creates objects with high overhead as needed.
3. ProtectionProxy controls access to the original object.
4. SmartReference replaces simple pointers and performs some additional operations when accessing objects.
5. When a persistent object is referenced for the first time, load it into the memory.
6. before accessing an actual object, check whether it is locked to ensure that other objects cannot change it.
Participants
1. Proxy
Save a reference so that the proxy can access the object. If the RealSubject and Subject interfaces are the same, the Proxy will reference the Subject.
Provides the same interface as the Subject interface, so that the proxy can be used to replace the object.
Controls the access to an object and may be responsible for creating and deleting it.
Other functions depend on the proxy type:
2. RemoteProxy is responsible for encoding requests and their parameters, and sending encoded requests to entities in different address spaces.
3. VirtualProxy can cache additional information of an object to delay its access.
4. ProtectionProxy checks whether the caller has the necessary access permissions to implement a request.
5. Subject
Define the common interfaces of RealSubject and Proxy, so that Proxy can be used in any place where RealSubject is used.
6. RealSubject
Define the entity represented by the Proxy.
Structure chart
Example: (java)
Package com. sql9.structured;
Abstract class CommonSubject {
Public abstract void request ();
}
Class ActualSubject extends CommonSubject {
Public ActualSubject (){
System. out. println ("Starting to construct ActualSubject ");
Try {
// Simulate doing some other work on the constructor
Thread. sleep (1000 );
System. out. println ("Sleeping 1 second finished ....");
} Catch (Exception ex ){
Ex. printStackTrace ();
}
System. out. println ("Finished constructing ActualSubject ");
}
@ Override
Public void request (){
System. out. println ("Executing request in ActualSubject ");
}
}
Class Proxy extends CommonSubject {
CommonSubject subject;
@ Override
Public void request (){
If (subject = null ){
Subject = new ActualSubject ();
}
Subject. request ();
}
}
Public class ProxyTest {
Public static void main (String [] args ){
CommonSubject subject = new Proxy ();
Subject. request ();
}
}
Result
Starting to construct ActualSubject
Sleeping 1 second finished ....
Finished constructing ActualSubject
Executing request in ActualSubject