Java design mode-Proxy)

Source: Internet
Author: User

Java design mode-Proxy)

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.
The class diagram is as follows:

Static code source code

public abstract class Subjects {    public abstract void operate();}
public class RealSubjects extends Subjects {    public void operate() {        System.out.println("do something...");    }}

Proxy

Public class ProxySubjects extends Subjects {private RealSubjects real = new RealSubjects (); public void operate () {// you can perform related operations before calling the target System. out. println ("before .... "); real. operate (); // you can perform related operations after calling the target System. out. println ("after .... ");}}

Client

public class Client {    public static void main(String[] args) {        Subjects subjects = new ProxySubjects();        subjects.operate();    }}

In our program design, we can also use the proxy mode to decouple the code that is composed of a series of irrelevant logic. For example, the log code in the Business Code can be performed in the proxy. Spring AOP is a typical dynamic proxy application.
Dynamic Proxy:
By observing the code above, we can find that each proxy class can only be an interface service. In this way, too many Proxies are generated in program development. Besides calling methods, all proxy operations are different, if all other operations are the same, the Code must be repeated. The best way to solve this problem is to use a dynamic proxy to complete all proxy functions through one proxy class .. When we encounter performance problems and do not want to make major changes to the code, we can use dynamic proxy.
JDK dynamic proxy contains a class and an interface:
InvocationHandler interface:
Public interface InvocationHandler {
Public Object invoke (Object proxy, Method method, Object [] args) throws Throwable;
}
Parameter description:
Object proxy: the proxy Object.
Method method: Method to be called
Object [] args: parameters required for method calling
The subclass of the InvocationHandler interface can be considered as the final operation class of a proxy, replacing ProxySubject.
Proxy class:
The Proxy class is an operation class dedicated to Proxy. You can use this class to dynamically generate an implementation class for one or more interfaces. This class provides the following operation methods:
Public static Object newProxyInstance (ClassLoader loader, Class

Public class BookFacadeFactory implements InvocationHandler {private Object target; /*** bind the delegate Object and return a proxy class * @ author Fu yuwei * @ time 08:52:05 * @ param target * @ return */public Object bind (Object target) {this.tar get = target; // gets the Proxy object and binds the interface. This is a defect. cglib makes up for this defect: return Proxy. newProxyInstance (target. getClass (). getClassLoader (), target. getClass (). getInterfaces (), this);} public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {Object result = null; System. out. println ("START transaction... "); result = method. invoke (target, args); System. out. println ("the transaction ends... "); return result;} public static void main (String [] args) {BookFacadeFactory proxy = new BookFacadeFactory (); BookFacade bookProxy = (BookFacade) proxy. bind (new BookFacacdeImpl (); bookProxy. addBook ();}}

JDK's dynamic proxy mechanism can only implement interface classes, but does not implement JDK's dynamic proxy for classes that do not implement interfaces. cglib implements proxy for classes, the principle is to generate a subclass for the specified target class and override the method to implement enhancement. However, because the class is inherited, the final modification class cannot be proxy.

Public class BookFacadeCglibProxy implements MethodInterceptor {private Object target; /*** create a proxy Object ** @ author Fu yuwei * @ time 09:17:34 * @ param target * @ return */public Object getInstance (Object target) {this.tar get = target; enhancer enhancer = new Enhancer (); enhancer.setSuperclass(this.tar get. getClass (); // callback method enhancer. setCallback (this); // create the proxy object return enhancer. create ();}/*** callback Method */public Object intercept (Object obj, Method arg1, Object [] arg2, MethodProxy proxy) throws Throwable {System. out. println ("START transaction... "); proxy. invoke (obj, arg2); System. out. println ("the transaction ends... "); return null;} public static void main (String [] args) {BookFacadeCglibProxy cglib = new BookFacadeCglibProxy (); BookFacadeCglibImpl bookCglib = (BookFacadeCglibImpl) cglib. getInstance (new BookFacadeCglibImpl (); bookCglib. addBook ();}}

Application Form of proxy mode:
(1) Remote Proxy-you can hide the fact that an object exists in a different address space. The client can also access objects on a remote machine. The remote machine may have better computing performance and processing speed, and can quickly respond to and process client requests.
(2) Virtual Proxy-allows objects with high memory overhead to be created as needed. This object is created only when it is actually needed.
(3) Copy-On-Write Proxy (Copy-On-Write Proxy)-used to control object replication by delaying object replication until the customer really needs it. Is a variant of the virtual proxy.
(4) Protection Proxy-provide different levels of target object Access permissions for different customers
(5) Cache Proxy-provides temporary storage for overhead computing results. It allows multiple customers to share results to reduce computing or network latency.
(6) Firewall Proxy-controls access to network resources and protects the subject from malicious customer attacks.
(7) SynchronizationProxy-Provides secure access to the topic in the case of multiple threads.
(8) Smart ReferenceProxy-provides some additional operations when an object is referenced, such as recording the number of calls to this object.
(9) Complexity HidingProxy: used to hide the Complexity of a complex set of classes and perform access control. It is also called the appearance proxy (Fa? Ade Proxy), which is not hard to understand. The complex hidden proxy and appearance mode are different because the proxy controls access, while the appearance mode is different because the proxy controls access, while the appearance mode only provides another set of interfaces.

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.