“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Static proxy mode

The proxy pattern provides a proxy way for objects to access and control their behavior

Scene: in the time of marriage scene layout and a few other things, generally can find marriage to celebrate the company to help agent, in your formal ceremony before doing after doing everything need not worry about, all to celebrate the marriage company can

public class StaticAgent { public static void main(String[] args) { WeddingCeremony weddingCeremony = new WeddingCeremony(new You()); weddingCeremony.happyMarry(); }} // void happyMarry(); } // class You Marry {@override public void happyMarry() {system.out.println ("小 test happy married "); } // WeddingCeremony implements Marry {private Marry target; Public WeddingCeremony(Marry target) {this.target = target; } @Override public void happyMarry() { before(); this.target.happyMarry(); after(); } private void before() {system.out.println (); } private void after() {system.out.println (); }}Copy the code

Viewing the Running result

The whole process is the wedding company to achieve the method of marriage, and not through the real role is really to get married to call directly

Conclusion:

Both the proxy object and the real object implement the same interface, and the proxy object represents the real role

So the realization of the static proxy mode to achieve the conditions

  1. True role

  2. The agent role

  3. Both roles implement the same interface

The advantage of this approach is that proxy objects can do a lot of things that real objects can’t, and real objects can do their own thing

Here’s how threads are created

New Thread (() - > System. Out. The println (" I love you "). The start ();Copy the code

This is the static proxy model

In the case of new Thread(), similar to the example of new WeddingCeremony(new You());

The WeddingCeremony class implements the Marry interface and the Thread class implements the Runnable interface

The happyMarry() method is defined on the Marry interface and the run() method is defined on the Runnable interface. methods

In Demo, happyMarry() is invoked to implement static proxy, and Thread is invoked to implement static proxy in the interface run method