Static proxy mode

Static proxy is the principle at the bottom of multithreading, Thread design in Java uses the static proxy design mode, wherein custom Thread class and Thread class are to achieve the Runable interface.

When the child thread is created, a reference to the custom thread class is passed in, and the run() method of the custom thread object is called by calling the start() method. The concurrent execution of threads is realized.

The profile

  • Both real objects and proxy objects implement the same interface
  • Proxy objects represent real roles
  • Real objects focus on their own functionality, proxy objects can help do other things

steps

  1. Defining an Abstract interface
  2. The class that defines the real object
  3. Defines the class of the proxy object
  4. The implementation method is invoked through a proxy object

The sample

public class StaticProxy {
    public static void main(String[] args) {
        Wedding wedding = new Wedding(newYou()); wedding.happyMarry(); }}interface Marry {
    void happyMarry(a);
}

// Real characters, you are the one getting married
class You implements Marry {
    @Override
    public void happyMarry(a) {
        System.out.println("You're getting married."); }}// Proxy role, help the target get married
class Wedding implements Marry {
    // Proxy targets, that is, real characters
    private Marry target;

    public Wedding(Marry target) {
        // Get the proxy target by constructing parameters
        this.target = target;
    }

    @Override
    public void happyMarry(a) {
        before();
        this.target.happyMarry();
        after();
    }

    private void before(a) {
        System.out.println("Before you get married, set the scene.");
    }

    private void after(a) {
        System.out.println("After the wedding, the closing money."); }}Copy the code

contrast

The executing code in the example above

Wedding wedding = new Wedding(new You());
wedding.happyMarry();
Copy the code

After simplification, we can obtain:

new Wedding(new You()).happyMarry();
Copy the code

And create a thread of code

new Thread(newRunnable() {... }).start();Copy the code

(simplified to a lambda expression) :

newThread(() -> ...) .start();Copy the code

New proxy (new real).