Java design pattern--proxy mode (proxies) __java design pattern

Source: Internet
Author: User
Tags throwable

Agent mode is the structure pattern of an object. The proxy mode provides a proxy object to an object, and the proxy object controls the reference to the original object.
The class diagram is as follows:

Static code Source

Public abstract class Subjects {public
    abstract void operate ();
}
public class Realsubjects extends Subjects {public

    void operate () {
        System.out.println (' Do something ... ');
    }

}

proxy class

public class Proxysubjects extends Subjects {

    private realsubjects real = new Realsubjects ();
    The public void operate () {
        ///
        System.out.println ("before ...")
        can be done before the target is invoked. Real.operate ();
        After the target can be invoked to do relevant operations
        System.out.println ("After ...");
    }

Client

public class Client {public

    static void Main (string[] args) {
        Subjects Subjects = new Proxysubjects ();
        Subjects.operate ();
    }

In our programming we can also use proxy mode to decouple code that is grouped together by a series of extraneous logic, such as the log code in the business code can be done in the broker. Spring's AOP is a typical dynamic proxy application.
Dynamic Proxy:
Observe that the above code can find that each proxy class can serve only one interface, so that many agents will inevitably be generated in the development of the program, and all the proxy operations are the same except for the method of the invocation. You must be repeating code at this point. The best way to solve this problem is to use a proxy class to complete all the agent functions, then you must do it using a dynamic proxy. When we encounter performance problems and do not want to make great changes to the code, we can use dynamic proxies.
The JDK dynamic proxy contains a class and an interface:
Invocationhandler Interface:
Public interface Invocationhandler {
Public Object invoke (OBJ ECT Proxy,method method,object[] args) throws Throwable;
}
Parameter Description:
Object proxy: The object being represented.
Methods: The method to invoke
Object[] args: The parameters required by the method invocation
can imagine subclasses of the Invocationhandler interface as the final action class of a proxy, replacing Proxysubject.
Proxy class:
The proxy class is a specialized action class that completes a proxy that enables you to dynamically build an implementation class for one or more interfaces, which provides the following action methods:
public static Object newproxyinstance ( ClassLoader Loader, Class

public class Bookfacadefactory implements {private Object target;
    /** * Binds the delegate object and returns a proxy class * @author Shu Yuwei * @time 2015-3-2 PM 08:52:05 * @param target * @return * *
        public object bind (Object target) {this.target = target; To get the proxy object to bind the interface, which is a flaw, cglib compensates for this defect return Proxy.newproxyinstance (Target.getclass (). getClassLoader (), target.getc
    Lass (). Getinterfaces (), this); public object invoke (object proxy, Method method, object[] args) throws Throwable {Object res
        Ult = null;
        System.out.println ("transaction begins ...");
        result = Method.invoke (target, args);

        System.out.println ("End of Transaction ...");
    return result;
        public static void Main (string[] args) {bookfacadefactory proxy = new Bookfacadefactory ();
        Bookfacade bookproxy = (bookfacade) proxy.bind (New Bookfacacdeimpl ());
    Bookproxy.addbook (); }

}

The

JDK's dynamic proxy mechanism can only broker classes that implement interfaces. A class that does not implement an interface cannot implement a dynamic proxy for JDK, which is a proxy for a class that generates a subclass of the specified target class and overrides the method implementation enhancements, but because of the inheritance, the cglib is used to implement the Therefore, the final decorated class cannot be represented.

public class Bookfacadecglibproxy implements Methodinterceptor {private Object target; /** * Create proxy object * @author Shu Yuwei * @time 2015-3-2 PM 09:17:34 * @param target * @return * * * Publ
        IC Object getinstance (object target) {this.target = target;
        Enhancer enhancer = new enhancer ();
        Enhancer.setsuperclass (This.target.getClass ());
        Callback method Enhancer.setcallback (this);
    Create proxy object return Enhancer.create ();  /** * Callback method/public object intercept (object obj, method arg1, object[] arg2, Methodproxy
        Proxy) throws Throwable {System.out.println ("transaction started ...");
        Proxy.invoke (obj, arg2);
        System.out.println ("End of Transaction ...");
    return null;
        public static void Main (string[] args) {bookfacadecglibproxy cglib = new Bookfacadecglibproxy ();
Bookfacadecglibimpl bookcglib = (Bookfacadecglibimpl) cglib.getinstance (New Bookfacadecglibimpl ());        Bookcglib.addbook (); }


}

proxy mode is applied in the form of
(1) Remote proxy-You can hide the fact that an object exists in a different address space. Also enables clients to access objects on remote machines, the remote machine may have better computational performance and processing speed, and can quickly respond to and process client requests.
(2) Virtual proxy-allows objects with large memory overhead to be created when needed. We only create when we really need this object. The
(3) write-time replication agent (Copy-On-Write proxy) – Used to control the replication of objects by delaying the replication of the object until the customer really needs it. is a variant of the virtual agent.
(4) Protection agent-provides different levels of target object access for different customers
(5) Cache proxy-provides temporary storage for costly operations results, allowing multiple customers to share results, Protection To reduce computation or network latency.
(6) firewall agent (Firewall proxy)-Controls access to network resources and protects topics from malicious customers.
(7) Synchronization agent (Synchronizationproxy) – Provides secure access to topics in multi-threaded situations.
(8) Smart Referenceproxy-When an object is referenced, provide some extra action, such as logging the number of calls to this object.
(9) Complex hidden agents (complexity hidingproxy)-the complexity of hiding a complex set of classes, and access control. Sometimes called the appearance agent (Façade proxy), this is not difficult to understand. Complex hidden agents and skin patterns are not the same because the proxy controls access and the appearance pattern is different because the proxy controls access and the skin mode provides only another set of interfaces.

Related Article

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.