java design pattern-proxy pattern

Keywords: JDK Programming Java Struts

Definition of proxy pattern

Provide a proxy for other objects to control access to this object

Roles in the proxy model

  • Subject abstract topic role: abstract topic class can be abstract class or interface, is the most common definition of business type, without special requirements.
  • RealSubject Specific Theme Roles: Also known as delegated roles, proxy roles. It is a big wrongdoer and a concrete executor of business logic.
  • Proxy Proxy Proxy Proxy Theme Roles: Also known as delegate and proxy classes. It is responsible for the application of real roles, delegates all the methods of abstract topic definition to real theme roles, and does pre-processing and post-processing after real theme roles are processed.

Static proxy mode

Implement a simple version to see the effect

When I was in school, I was fascinated by the game of LOL. The new heroes in the game were 6,300 gold coins to buy, but one game got 100 gold coins in 20 to 30 minutes. To buy a hero, you need to spend a lot of time on the game. Long game time, backache, dry eyes, sore hands and feet, etc., Internet addiction syndrome came out. What can we do? I want to play games, but I don't want to touch the trouble of computer too long. How can I solve it? There's a way. There are so many companies that play games. I just give them my account number and let them help me win gold coins. I just enjoy the fun that I want to play that hero and then play that hero.

Code List: Define Gamer Interface

public interface ILOL {
    //Sign in
    public void login(String user,String password);
    //Choosing Man-Machine Fighting
    public void battle();
    //Acquire gold coins
    public void gold();
}

Code List: Gamer Implementation Class

public class LOL implements ILOL{

    private static String name = null;

    public LOL(String name){
        this.name = name;
    }
    @Override
    public void login(String user,String password) {
        System.out.println("Login name"+user+"Users"+this.name+"Successful login");
    }
    @Override
    public void battle() {
        System.out.println("Choose the man-machine mode and start the war");
    }
    @Override
    public void gold() {
        System.out.println("Get 100 Game Coins");
    }
}

Code List: The Player Operates Normally

public class Test {
    public static void main(String[] args) {
        LOL user = new LOL("Zhang San");
        //Sign in
        user.login("zhangsan","123456");
        System.out.println("start time"+new Date());
        //Begin man-machine combat
        user.battle();
        //Acquire gold coins
        user.gold();
        System.out.println("Ending time"+new Date());
    }
}

Look at the results.

Zhang San, a user named zhangsan, successfully logged in
 Start time Fri May 12 17:58:28 CST 2017
 Choose the man-machine mode and start the war
 Get 100 Game Coins
 End time Fri May 12 17:58:28 CST 2017

Code List: Define Proxy Interface

public class GameLOL implements ILOL{
    private  ILOL iLOL;
    public GameLOL(ILOL ilol){
        this.iLOL=ilol;
    }
    //Substitute login
    public void login(String user, String password) {
        iLOL.login(user,password);
    }
    //Man-machine combat on behalf of training
    public void battle() {
        iLOL.battle();
    }
    //Acquisition of gold coins on behalf of training
    public void gold() {
        iLOL.gold();
    }
}

Code List: Calling Game Agents

public class Test {
    public static void main(String[] args) {
        //My account
        ILOL user = new LOL("Zhang San");
        //Determine the substitute training
        GameLOL gameLOL = new GameLOL(user);
        //Substitute login
        gameLOL.login("zhangsan","123456");
        System.out.println("start time"+new Date());
        //Start man-machine combat on behalf of training
        gameLOL.battle();
        //Getting gold coins for me
        gameLOL.gold();
        System.out.println("Ending time"+new Date());
    }
}

Let the game agent help you to practice the results

Zhang San, a user named zhangsan, successfully logged in
 Start time Fri May 12 18:00:08 CST 2017
 Choose the man-machine mode and start the war
 Get 100 Game Coins
 Closing time Fri May 12 18:00:08 CST 2017

Dynamic Agent Model

The proxy mode we implement ourselves belongs to the static proxy mode. Dynamic proxy does not care who the proxy is, but specifies the proxy object at run time. Now there is a popular name called Aspect-Oriented Programming AOP, whose core is to adopt the dynamic proxy mode, since it is so important. Let's see how it works.

In the dynamic proxy mechanism of java, there are two important classes or interfaces, one is Invocation Handler (Interface) and the other is Proxy(Class). This class and interface is necessary to realize our dynamic proxy.

Code List: Define a dynamic proxy class

public class GameProxyH implements InvocationHandler {
    private Object obj = null;
    public GameProxyH(Object _obj){
        this.obj = _obj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object invoke = method.invoke(obj, args);
        return invoke;
    }
}

Code List: Calling Dynamic Proxy Classes

public class Test {
    public static void main(String[] args) {
        //The Real Object of Agent
        ILOL user = new LOL("Zhang San");
        //If we want to proxy which real object, we pass it in and finally call its method through the real object.
        GameProxyH gameProxyH = new GameProxyH(user);
        //Here we use gameProxyH class ClassLoader object to load our proxy object
        ClassLoader cl = gameProxyH.getClass().getClassLoader();
        //Generate a proxy class dynamically
        ILOL instance = (ILOL)Proxy.newProxyInstance(cl, user.getClass().getInterfaces(), gameProxyH);
        //Land
        instance.login("zhangsan","password");
        System.out.println("start time"+new Date());
        //Start man-machine combat on behalf of training
        instance.battle();
        //Getting gold coins for me
        instance.gold();
        System.out.println("Ending time"+new Date());
    }
}

Look at the console output

Zhang San, a user named zhangsan, successfully logged in
 Start time Mon May 15:55:20 CST 2017
 Choose the man-machine mode and start the war
 Get 100 Game Coins
 Closing time Mon May 15:55:20 CST 2017

Advantages and disadvantages of proxy model

Advantage

  • Clear responsibilities: The real role is to achieve the actual business logic, do not care about other non-responsibility of the business, through the late agent to complete a business, with the result that the programming is concise and clear.
  • High scalability: The specific theme role will change at any time. As long as it implements the interface, regardless of how it changes, it can not escape the palm of the Tara Buddha (interface), then our proxy class can be completely used without any modification.
  • Intelligence: This has not been mentioned in our previous explanations, but in the following chapter on dynamic agents, you will see that interested readers of Agent Intelligence can also see how Struts maps form elements to objects.

Disadvantages

  • Adding a proxy object to the client and the target object will slow down request processing.

  • The complexity of the system is increased.

Proxy mode usage scenarios

When I saw the code that introduced the proxy mode on the internet, my first feeling was why I used the proxy. Let's think about why we need a lawyer in a lawsuit in real life, because you don't want to be involved in a quarrel. You just have to tell the lawyer what you really are. Other matters such as pre-investigation and post-investigation are handled properly by lawyers. You just stay at home and listen to the news.

ps

AOP source code uses two kinds of dynamic proxies to implement interception and entry functions: jdk dynamic proxy and cglib dynamic proxy. Both methods exist at the same time, and each has its own advantages and disadvantages. jdk dynamic proxy is made by Java The internal reflection mechanism is realized, and the bottom layer of cglib dynamic agent is realized by using asm. Generally speaking, reflection mechanism is more efficient in the process of class generation, while ASM is more efficient in the related execution process after class generation (the inefficient problem of class generation process can be solved by caching the classes generated by asm). It is also important to note that the application premise of jdk dynamic proxy must be that the target class is based on a unified interface. Without the preconditions mentioned above, jdk dynamic proxy cannot be applied. It can be seen that jdk dynamic agent has some limitations. cglib, a third-party class library, is more widely used and has more advantages in efficiency.

Posted by kpowning on Sun, 30 Jun 2019 16:15:38 -0700