Java uses the proxy pattern in design pattern to build an instance of the project show _java

Source: Internet
Author: User
Tags reflection

Concept

Proxy mode (proxy): Proxy mode is actually more than one proxy class out, for the original object to do some operations. For example, I sometimes need to ask a lawyer, because lawyers have expertise in the law, can be used for my operation to express my ideas, this is the meaning of the agency. The agent mode is divided into two categories: 1, static proxy (not using the method inside JDK), 2, dynamic Proxy (using the Invocationhandler and proxy in JDK).
The static proxy is created by the programmer or the tool generates the source code of the proxy class and then compiles the proxy class. The so-called static is also in the program before the operation of the byte code file, proxy class and the relationship between the delegate class is determined before running.
The source code of the dynamic proxy class is generated dynamically by the JVM based on the reflection mechanism during the program running, so there is no bytecode file for the proxy class. The relationship between the proxy class and the delegate class is determined when the program is run.

Example
Here we give an example of a static proxy:
Class Diagram:

/** 
 * Player Interface * * */public 
interface Igameplayer { 
 
  //login game public 
  void Login (string user, String password); 
 
  Kill the strange, the main characteristic of the network game is public 
  void Killboss (); 
 
  Upgrade public 
  void Upgrade (); 
 
} 

/** * Player * */public class Gameplayer implements-igameplayer {private Stri 
 
  ng name = ""; 
  Passing the name public Gameplayer (String _name) {this.name = _name through the constructor; //Play Strange, the most expected is to kill the old blame public void Killboss () {System.out.println (THIS.name + "In play strange!") 
 
  ");  You must log in before you enter the game. public void Login (string user, string password) {System.out.println ("Logon name" + User + "The role" + THIS.name + "Login success!" 
  "); //upgrade, there are many ways to upgrade, money to Buy is a kind of, do the task is also a public void upgrade () {System.out.println (THIS.name +) rose again! 
  "); } 
 
} 

/** * Client is not visible to the proxy object/public class Gameplayerproxy implements-Igameplayer {p Rivate Igameplayer Gameplayer = null;//the proxy object//via constructor pass to whom leveling public gameplayerproxy (String username) {Thi 
  S.gameplayer = new Gameplayer (username); 
  }//Leveling kill strange public void Killboss () {This.gamePlayer.killBoss (); 
  ///Leveling login public void login (string user, string password) {this.gamePlayer.login (user, password); 
  }//Leveling upgrade public void Upgrade () {This.gamePlayer.upgrade (); }} 

 
 * * Client is not visible to the proxy object/public 
class GamePlayerProxy2 implements Igameplayer { 
 
  private Igameplayer Gameplayer = null;//the proxy object 
 
  //via constructor pass to whom leveling public 
  GamePlayerProxy2 (String username) { 
    This.gameplayer = New Gameplayer (username); 
  } 
 
  Leveling kill strange public 
  void Killboss () { 
    this.gamePlayer.killBoss (); 
  } 
 
  Leveling login public 
  void Login (string user, string password) { 
    System.out.println ("Logon time is:" + new Date (). toLocaleString ()); 
    This.gamePlayer.login (user, password); 
 
  Leveling upgrade public 
  void Upgrade () { 
    this.gamePlayer.upgrade (); 
    SYSTEM.OUT.PRINTLN ("Upgrade time is:" + new Date (). toLocaleString ()); 
  } 
 
 


* * * Client is not visible to the proxy object/public class GamePlayerProxy3 {private Igameplayer gameplayer; 
     Passed by the constructor to the leveling (proxy) object public GamePlayerProxy3 (Igameplayer gameplayer) {this.gameplayer = Gameplayer; 
  System.out.println ("I am a leveling, I play the role is someone else, can be dynamically passed in"); Public Igameplayer GetProxy () {return (Igameplayer) proxy.newproxyinstance (This.getclass (). getClassLoader () 
  , New Class[]{igameplayer.class}, New Myinvocationhandler ()); Private class Myinvocationhandler implements Invocationhandler {@Override public Object invoke (objec T proxy, method method, object[] args throws Throwable {if (Method.getname (). Equals ("Login")) {SYSTEM.O 
      UT.PRINTLN ("Logon time is:" + new Date (). toLocaleString ()); 
      } if (Method.getname (). Equals ("Upgrade")) {System.out.println ("Upgrade time is:" + new Date (). toLocaleString ()); 
      } method.invoke (Gameplayer, args); 
    return null; } 
     
  } 
}


public class Test {public static void main (string[] args) {* * normal static proxy: client does not know the proxy object, the proxy object completes its function call 
    * * Igameplayer proxy = new Gameplayerproxy ("X"); 
    System.out.println ("Start time is:" + new Date (). toLocaleString ()); 
    Proxy.login ("Zhangsan", "ABCD"); 
    Proxy.killboss (); 
    Proxy.upgrade (); 
     
    System.out.println ("End time is:" + new Date (). toLocaleString ()); 
     
    System.out.println (); 
    * * Agent object enhances the function of the agent/igameplayer Proxy2 = new GamePlayerProxy2 ("M"); 
    Proxy2.login ("Lisi", "EFG"); 
    Proxy2.killboss (); 
     
    Proxy2.upgrade (); 
     
    System.out.println (); * * Dynamic Agent: Using the Invocationhandler provided by JDK, reflection invokes the method of the proxy object * Combining Java.reflect.Proxy to generate proxy objects * Dynamically passing in the proxy object construction Invocationha Ndler, when invoke in handler can enhance the function of the method of the proxy object * or say: (Facing section:) where (the connection point), performing what Behavior (notification) * GamePlayerProxy3 when the method name is login when the notification starts 
    , upgrade notification end time/GamePlayerProxy3 dynamic = new GamePlayerProxy3 (New Gameplayer ("Y")); IGameplayer Dynamicplayer = Dynamic.getproxy (); 
    Dynamicplayer.login ("Wangwu", "1234"); 
    Dynamicplayer.killboss (); 
    Dynamicplayer.upgrade (); 
 * * Facing section: Some similar business logic needs to be added in many places, that they can extract it into the cut, the section is the transaction section: such as log section, permission section, Business section/}}

Print:

Start time is: 2014-10-8 17:19:05 
Login named Zhangsan role x Login success! 
X is playing strange! 
X has risen again! The 
end time is: 2014-10-8 17:19:05 
 
logon time is: 2014-10-8 17:19:05 
login named Lisi role m login success! 
M playing the strange! 
M up a level again! 
upgrade time is: 2014-10-8 17:19:05 
 
I am a leveling, I play the role is someone else, you can dynamically pass in the 
login time is: 2014-10-8 17:19:05 
login name Wangwu role Y Login Successful! 
Y are playing weird! 
upgrade time is: 2014-10-8 17:19:05 
Y got a level again! 


Advantages
(1) Clear responsibilities
The real role is to implement the actual business logic, do not care about other non-this responsibility of the transaction, through the late agent to complete a transaction, with the result is simple and clear programming.
(2) Proxy objects can act as intermediary between client and target object, thus playing a role and protecting the target object.
(3) High scalability

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.