Design Pattern _ proxy pattern

Source: Internet
Author: User

Design Pattern _ proxy pattern


The proxy acts as an intermediary between the client and the target object, and can remove content and services that the customer cannot see or add additional services required by the customer through the proxy object, such

Interceptor, network proxy, and wall flip in structs2.

I will not describe other advanced proxy models here. I learned a little superficial and did not apply them to projects. This summer vacation just broadened my horizons and impressed myself.

Normal proxy (static proxy)

 

public abstract class IGamePlayer { public abstract void fightBoss(); public abstract void login(String uname,String pwd); public abstract void upgrade();}

Public class GamePlayer extends IGamePlayer {private String name =; public GamePlayer (String name) {this. name = name ;}@ Override public void fightBoss () {System. out. println (this. name + hitting);} @ Override public void upgrade () {System. out. println (this. name + upgraded);} @ Override public void login (String uname, String pwd) {System. out. println (uname + logon, time + new Date ());}}

Public class GamePlayerProxy extends IGamePlayer {private IGamePlayer gamePlayer = null; public GamePlayerProxy (GamePlayer gamePlayer) {this. gamePlayer = gamePlayer;} @ Override public void fightBoss () {this. gamePlayer. fightBoss () ;}@ Override public void login (String uname, String pwd) {this. before (); this. gamePlayer. login (uname, pwd) ;}@ Override public void upgrade () {this. gamePlayer. upgrade (); this. after ();} public void before () {System. out. println (start proxy);} public void after () {System. out. println (end proxy );}}

Public class Client {public static void main (String [] args) {GamePlayer player = new GamePlayer (dabao); GamePlayerProxy proxy = new GamePlayerProxy (player); proxy. login (dabao, a); proxy. fightBoss (); proxy. upgrade ();}}

The above example is very simple. It feels a bit like getting started.

 

The following is an interesting proxy called forced proxy, which means that the proxy can only be found through the real class, and the static proxy above finds the real class through the proxy to achieve the purpose of access.

 

Force proxy

 

// Force the proxy to find the proxy through the real class // common proxy find the real class public abstract class IGamePlayer {public abstract void fightBoss (); public abstract void login (String uname, string pwd); public abstract void upgrade (); public abstract IGamePlayer getProxy ();}

Public class GamePlayerProxy extends IGamePlayer {private IGamePlayer gamePlayer = null; public GamePlayerProxy (IGamePlayer gamePlayer) {this. gamePlayer = gamePlayer;} @ Overridepublic void fightBoss () {this. gamePlayer. fightBoss () ;}@ Overridepublic void login (String uname, String pwd) {this. before (); this. gamePlayer. login (uname, pwd) ;}@ Overridepublic void upgrade () {this. gamePlayer. upgrade (); this. after ();} public void before () {System. out. println (start proxy);} public void after () {System. out. println (end proxy);} // No, It is yourself @ Overridepublic IGamePlayer getProxy () {return this ;}}

Public class GamePlayer extends IGamePlayer {private String name =; private IGamePlayer proxy = null; @ Overridepublic IGamePlayer getProxy () {this. proxy = new GamePlayerProxy (this); return this. proxy;} public GamePlayer (String name) {this. name = name ;}@ Overridepublic void fightBoss () {if (this. isProxy () {System. out. println (this. name +);} else {System. out. println (Please use the specified proxy for access); }}@ Overridepublic void upgrade () {if (this. isProxy () {System. out. println (this. name + upgraded);} else {System. out. println (Please use the specified proxy for access); }}@ Overridepublic void login (String uname, String pwd) {if (this. isProxy () {System. out. println (uname + logon, time + new Date ();} else {System. out. println (Please use the specified proxy for access);} private boolean isProxy () {if (this. proxy = null) {return false;} else {return true ;}}}

Public class Client {public static void main (String [] args) {/* GamePlayer player = new GamePlayer (dabao); player. login (dabao, a); player. fightBoss (); player. upgrade (); * // * IGamePlayer player = new GamePlayer (dabao); IGamePlayer proxy = new GamePlayerProxy (player); proxy. login (dabao, a); proxy. fightBoss (); proxy. upgrade (); */IGamePlayer player = new GamePlayer (dabao); IGamePlayer proxy = player. getProxy (); proxy. login (dabao, a); proxy. fightBoss (); proxy. upgrade ();}}

 

Analysis Test

The first one directly uses real-class access, which naturally cannot be accessed. Because the proxy is specified in the business method.

The second method is to get a proxy object through the real class. In this way, the real class is accessed through the proxy, which is the same as the static proxy.

Third, get a proxy object through the real class, and then implement access.

 

Dynamic proxy

It can be roughly divided into four steps, with more details. Refer to the blog. Http://www.cnblogs.com/flyoung2008/archive/2013/08/11/3251148.html

1. Use the InvocationHandler interface to create your own call processor IvocationHandler handler = new InvocationHandlerImpl (...);
2. Create a dynamic Proxy class by specifying a ClassLoader object and a group of interfaces for the Proxy class
Class clazz = Proxy. getProxyClass (classLoader, new Class [] {...});
3. Get the constructor of the dynamic proxy class through the reflection mechanism. The parameter type is the type of the called processor interface.
Constructor constructor = clazz. getConstructor (new Class [] {InvocationHandler. class });
4. Create a proxy instance by using the constructor. At this time, the called processor object must be passed in as a parameter.
Interface Proxy = (Interface) constructor. newInstance (new Object [] (handler ));
To simplify the object creation process, the newInstance method in the Proxy class encapsulates 2 ~ 4. You can create a proxy object in two steps.
The generated ProxySubject inherits the Proxy class to implement the Subject interface. The implemented Subject method actually calls the invoke method of the processor, the invoke method uses reflection to call the method of the proxy Object (Object result = method. invoke (proxied, args ))

 

 

Public class GamePlayIH implements InvocationHandler {// Class cls = null; // The proxy Object obj = null; // The proxy instance public GamePlayIH (Object _ obj) {this. obj = _ obj;} public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {Object result = method. invoke (this. obj, args); if (method. getName (). repeated signorecase (login) {System. out. println (someone logged in with my account);} return result ;}}

 

 

 

Public static void main (String [] args) {GamePlayer player = new GamePlayer (dabao); InvocationHandler handler = new GamePlayIH (player); ClassLoader cl = player. getClass (). getClassLoader (); IGamePlayer proxy = (IGamePlayer) Proxy. newProxyInstance (cl, new Class [] {IGamePlayer. class}, handler); proxy. login (dabao, a); proxy. fightBoss (); proxy. upgrade ();}

 

Here, we need to note that Proxy only supports interface Proxy. That is to say, IGamePlayer can only be an interface, not an abstract class. You may find that all the above statements use abstract classes. After careful consideration, we can find that I didn't use Polymorphism or make mistakes when instantiating GamePlayer (dabao. In this case, dynamic proxy is completely interface-oriented and abstract-layer underlying programming.

 

public interface IGamePlayer {public void fightBoss();public void login(String uname, String pwd);public void upgrade();}

Public class GamePlayer implements IGamePlayer {private String name =; public GamePlayer (String name) {this. name = name;} public void fightBoss () {System. out. println (this. name + hitting);} public void login (String uname, String pwd) {System. out. println (uname + logon, time + new Date ();} public void upgrade () {System. out. println (this. name + upgrade );}}

 

 

Integrate the above processes

 

Public class DynamicProxy
 
  
{Public static
  
   
T newProxyInstance (ClassLoader loader, Class
   [] Interfaces, InvocationHandler h) {// searches for JoinPoint connection points. The AOP framework uses metadata to define if (true) {// XXX to execute System. out. println (executed here);} return (T) Proxy. newProxyInstance (loader, interfaces, h );}}
  
 

Further sorting

 

 

public class SubjectDynamicProxy extends DynamicProxy {public static 
 
   T  newProxyInstance(IGamePlayer gamePlayer){ClassLoader loader=gamePlayer.getClass().getClassLoader();Class
  [] interfaces=gamePlayer.getClass().getInterfaces();InvocationHandler handler=new GamePlayIH(gamePlayer);return newProxyInstance(loader, interfaces, handler); }}
 


 

Call

 

Public static void main (String [] args) {GamePlayer player = new GamePlayer (dabao); InvocationHandler handler = new GamePlayIH (player); IGamePlayer proxy = DynamicProxy. newProxyInstance (player. getClass (). getClassLoader (), player. getClass (). getInterfaces (), handler); proxy. login (dabao, a); proxy. fightBoss (); proxy. upgrade ();}


 

 

Public static void main (String [] args) {GamePlayer player = new GamePlayer (dabao); IGamePlayer proxy = SubjectDynamicProxy. newProxyInstance (player); proxy. login (dabao, a); proxy. fightBoss (); proxy. upgrade ();}

I'm a cainiao. I'm on the road.

 

 

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.