[Dark Horse Programmer Jinan Center] Proxy Mode - Static Proxy

[Dark Horse Programmer Jinan Center] Proxy Mode -
Static Proxy Proxy is a design mode that provides another way of accessing the target object; that is, accessing the target object through the proxy object. On the basis of the realization, enhance the additional function operation, that is, extend the function of the target object.
In the java language, the proxy mode is divided into three types: static proxy, dynamic proxy, and Cglib proxy.
Today, let me talk to you about the first mode of the proxy mode - the static proxy mode.
When a static proxy is used, it is necessary to define an interface or a parent class. The proxied object and the proxy object implement the same interface or inherit the same parent class.
So how do we use the static proxy mode? First create an interface (JDK proxies are all interface-oriented), and then create a specific implementation class to implement this interface. When creating a proxy class, the interface is also implemented. The difference is that the methods defined in the interface need to be defined in the interface. The business logic function of the method is realized, and the method in the proxy class only needs to call the corresponding method in the specific class, so that we can directly call the method of the proxy class when we need to use the function of a method in the interface. The implementation class is hidden under the hood.
Step 1: Define the general interface Iuser.java
public interface Iuser {3 void eat(String s);4 }
Step 2: Create a concrete implementation class UserImpl.java
public class UserImpl implements Iuser {
  @Override
  public void eat(String s) {
    System.out.println("I want to eat" +s);
  }
} Step 3: Create a proxy class UserProxy.java
public class UserProxy implements Iuser {
  private Iuser user = new UserImpl();
  @Override
  public void eat(String s) {
    System.out.println("Static proxy prepended content");
    user.eat(s);
    System.out .println("Static proxy post content");
  }
}
Step 4: Create a test class ProxyTest.java
public class ProxyTest {
  public static void main(String[] args) {
    UserProxy proxy = new UserProxy();
    proxy.eat ("Apple");
  }
}
Today, I'm just briefly talking about the static proxy mode with you. You must practice more to better apply it to our development.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326912048&siteId=291194637