当前位置:网站首页>Static proxy of proxy mode

Static proxy of proxy mode

2022-07-07 02:47:00 Xiaobai without work

1: Static proxy concept

Wrap the object with a proxy object , Then replace the object with the proxy object ,
Any call to the original object must pass through the proxy object , Proxy object decision When Method to call the original object 【 Polymorphic features used ( Subclass references point to parent objects , When executing methods , Is the code that executes subclasses )】

2: Static proxy features

2.1: Fixed target role 【 It must be an object that implements the specified interface or class !!!
2.2: Get the target role before the application executes
2.3: Proxy objects enhance the behavior of the target object
2.4: There may be multiple agents cause " Class blast "( shortcoming ) shortcoming : The proxy object and the target object need to implement the same interface

3: Code implementation

3.1: Write a common interface , Define the behavior method name

public interface Marry {
    
    public void toMarry();
}

3.2: Define target object class , Implementation interface

/***  Static proxy  ——>  Target audience  */
public class You implements Marry{
    
    @Override
    public void toMarry() {
    
        System.out.println(" I'm getting married ");
    }
}

3.3: Define proxy class , Implementation interface

/** *  This agent , Only proxy can be implemented Marry Object of the interface  */
public class MarryCompanyProxy implements Marry{
    
    //  Target audience 
    private Marry marry;
    //  The target object is passed in through the constructor 
    public MarryCompanyProxy(Marry marry) {
    
        this.marry = marry;
    }
    @Override
    public void toMarry() {
    
    //  Reinforcement behavior 
        before();
    //  Execute methods in the target object 
        marry.toMarry();
    //  Reinforcement behavior 
        after();
    }
    /***  Reinforcement behavior  */
    private void after() {
    
      System.out.println(" Happy wedding , have a lovely baby early !");
    }
    /***  Reinforcement behavior  */
    private void before() {
    
        System.out.println(" The site is being arranged ...");
    }
}

3.4: Code testing

public class Test {
    
    public static void main(String[] args) {
    
        You you = new You();
        MarryCompanyProxy marryCompanyProxy = new MarryCompanyProxy(you);
        marryCompanyProxy.toMarry();
    }
}
原网站

版权声明
本文为[Xiaobai without work]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130857397536.html