Java design mode-proxy mode, java design mode proxy

Source: Internet
Author: User

Java design mode-proxy mode, java design mode proxy
Proxy Design Mode

Proxy design mode: provides a proxy for other objects to control access to this object.
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.
Proxy design pattern structure diagram:

Role of classes or interfaces in proxy mode:

  • Abstract topic role (Subject): it can be an abstract class or an interface, and is the most common business type definition. Declares the common interfaces of a specific topic role and a proxy topic role.
  • A specific topic role (RealSubject) is also called a delegated role or a delegated role. It is the actual executor of the business logic.
  • Proxy topic role (Proxy) is also called the delegate class and Proxy class. It is responsible for the application of real themes. The proxy topic role contains references of specific topic roles, so that the target objects can be operated at any time; the proxy topic role provides the same interface as a specific topic role to replace a specific topic role at any time. The proxy topic role usually performs some other operations before or after the client calls the role to a specific topic, rather than simply passing the call to the target object.

When do I use the proxy mode? When we do not want to directly operate the target class or want to perform some additional operations on the method access of the target class, we can consider using the proxy mode.

The code model is as follows:

// Abstract topic class: Define a request method interface Subject {public void request () ;}// real topic class: normal business implementation class, implemented the Subject Interface class RealSubject implements Subject {public void request () {System. out. println ("RealSubject request") ;}} class Proxy implements Subject {private Subject subject; public Proxy (Subject subject) {this. subject = subject ;}@ Override public void request () {doBefore (); subject. request (); doAfter () ;}// pre-processing private void doBefore () {System. out. println ("RealSubject request before");} // private void doAfter () {System. out. println ("RealSubject request after ");}}

Here, the doBefore and doAfter methods are pre-processed and post-processed during method calling.

Proxy implementation:

Take playing games as an example. For example, if we want to play the League of legends (LOL) in qualifying, the premise is that we want to reach 30 levels, so we don't want to play games by ourselves, you can try it out (the profits in this industry are very impressive ). The specific code is described as follows:

Interface IGamePlayer {void playGame ();} class GamePlayer implements IGamePlayer {private String name; public GamePlayer (String name) {this. name = name;} public void playGame () {System. out. println (name + "playing");} class GamePlayerProxy implements IGamePlayer {private IGamePlayer gamePlayer; public GamePlayerProxy (IGamePlayer gamePlayer) {this. gamePlayer = gamePlayer;} @ Override public void playGame () {gamePlayer. playGame () ;}} public class Test {public static void main (String [] args) {IGamePlayer gamePlayer = new GamePlayer ("James "); gamePlayerProxy gamePlayerProxy = new GamePlayerProxy (gamePlayer); gamePlayerProxy. playGame ();}}

If you do not directly use the instance of the real role GamePlayer, you can still play the game. This trainer role is the GamePlayerProxy class.

Common proxy

In the above example, we have a new real role GamePlayer and then pass it to the proxy class GamePlayerProxy. In this way, the real role does not need to work, and all the operations are done by the proxy. A common proxy requires the client to only access the proxy role, but not the real role.

/*** Common Proxy: we need to know the existence of the proxy before we can access * The client must only access the proxy role, but cannot access real roles * @ author qhyuan1992 **/interface IGamePlayer {void playGame ();} class GamePlayer implements IGamePlayer {private String name; public GamePlayer (String name) {this. name = name;} public void playGame () {System. out. println (name + "playing") ;}} class GamePlayerProxy implements IGamePlayer {private IGamePlayer gamePlayer; public GamePlayerProxy (String name) {gamePlayer = new GamePlayer ("zhangsan ");} @ Override public void playGame () {gamePlayer. playGame () ;}} public class Test {public static void main (String [] args) {GamePlayerProxy gamePlayerProxy = new GamePlayerProxy ("James"); gamePlayerProxy. playGame ();}}

The change is to specify the proxy class in the proxy constructor. In this way, the code is more concise. For callers, they only need to know the existence of the proxy instead of who the proxy is. The impact of changes to real topic roles on upper-Layer Code is shielded. Changes to real topic roles will not affect the upper-layer code.

Force proxy

Generally, you need to find the real role through the proxy, but force the proxy is required, you must find the proxy role through the real role, otherwise you cannot access it: whether it is through the proxy class or through the real role.

/*** Force Proxy: you must find the proxy role through the real role; otherwise, you cannot access the proxy role. * No proxy class or real role can be used to access * @ author qhyuan1992 **/interface IGamePlayer {void playGame (); public IGamePlayer getProxy ();} class GamePlayer implements IGamePlayer {private String name; private IGamePlayer proxy; public GamePlayer (String name) {this. name = name;} public void playGame () {if (isProxy () {System. out. println (name + "playing");} else {System. out. println ("Please use the specified proxy to access") ;}} public IGamePlay Er getProxy () {proxy = new GamePlayerProxy (this); return proxy;} private boolean isProxy () {return this. proxy! = Null ;}} class GamePlayerProxy implements IGamePlayer {private IGamePlayer gamePlayer; public GamePlayerProxy (IGamePlayer gamePlayer) {this. gamePlayer = gamePlayer;} @ Override public void playGame () {gamePlayer. playGame () ;}@ Override public IGamePlayer getProxy () {return this ;}} public class Test {public static void main (String [] args) {// 1. inaccessible: you must use a proxy to access a real role. If you use a real role to access it directly, you cannot access IGamePlayer gamePlayer = new GamePlayer ("zhangsan"); gamePlayer. playGame (); // 2. inaccessible: Use the proxy class // new proxy instead of the proxy IGamePlayer gamePlayer = new GamePlayer ("zhangsan"), GamePlayerProxy gamePlayerProxy = new GamePlayerProxy (gamePlayer), and gamePlayerProxy. playGame (); // 3. accessible: Use the proxy IGamePlayer gamePlayer = new GamePlayer ("zhangsan") returned by the real role; GamePlayerProxy = (GamePlayerProxy) gamePlayer. getProxy (); proxy. playGame ();}}
Dynamic proxy

The proxy we previously wrote is static proxy.
Static proxy problems: Imagine if the Subject interface changes. The proxy class and specific target implementations must be changed, but not very flexible.
A dynamic proxy is an object that is specified by the agent only in the running stage, instead of caring about the proxy.
Using the built-in functions of Java to support proxy mode is no problem.

JDK1.3 provides support for dynamic proxy. The InvocationHandler interface is a dynamic proxy interface provided by JDK to proxy the method of the proxy class.

Benefits of dynamic Proxy:

  • The obvious difference between dynamic proxy and static proxy is that many methods are defined on the Subject interface during the implementation of static proxy, and many methods need to be implemented in the proxy class; while many methods are defined in Subject, the dynamic proxy class always has only one invoke method. In this way, when the Subject interface changes. The dynamic proxy interface does not need to be changed.
  • Dynamic proxy can process requests more conveniently.
/*** Dynamic Proxy: Specifies the proxy object in the running stage, instead of caring about the proxy. * Static proxy * @ author qhyuan1992 */interface IGamePlayer {void playGame ();} class GamePlayer implements IGamePlayer {private String name; public GamePlayer (String name) {this. name = name;} public void playGame () {System. out. println (name + "playing");} class GamePlayIH implements InvocationHandler {// The Object obj of the proxy instance; // The proxy owner public GamePlayIH (Object obj) {this. obj = obj;} // call the proxy Method @ Override public Object invoke (Object proxy, method Method, Object [] args) throws Throwable {doBefore (); object result = method. invoke (obj, args); doAfter (); return result;} private void doAfter () {System. out. println ("called");} private void doBefore () {System. out. println ("before call") ;}} public class Test {public static void main (String [] args) {IGamePlayer player = new GamePlayer ("James "); invocationHandler handler = new GamePlayIH (player); IGamePlayer proxy = (IGamePlayer) Proxy. newProxyInstance (player. getClass (). getClassLoader (), new Class [] {IGamePlayer. class}, handler); proxy. playGame ();}}

Output:

Before calling
John is playing
After the call

Reference: Zen/JAVA and patterns of design patterns

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.