7. Multithreading (static proxy mode (implement the Runnable interface to create threads))

Multithreading (static proxy mode (implement the Runnable interface to create threads))

  1. Both the real object and the proxy object must implement the same interface
  2. Proxy objects to act on behalf of real objects
  3. Benefit: Proxy objects can do things that real objects cannot

         Real objects focus on their own business

Example: The way we learned earlier to implement the Runnable interface to create threads uses the proxy mode (when creating in the main thread), that is

Thread(race, "rabbit").start.

Here Thread (which implements the Runnable interface) and the race both implement the Runnable interface. So Thread is the proxy, and the race in it is the target object (he is focusing on his rewritten run method, he can't start the thread with .start), so use the proxy of Thread to start the thread with .start().

 

 

Marriage example:

 

Let's think about it here:

  1. The You and Wed classes here both implement the Marry interface. There is an abstract method HappyMarry in the interface. You is the real object, Wed is the proxy object (he needs to pass in a real object, here is the target (the construction method passes parameters to him)) Wed has completed many methods that are not there.

 

 

 

 

package org.example;

import sun.rmi.runtime.NewThreadAction;

public class StaticProxy {
    public static void main(String[] args) {
        You you = new You();
//        new Thread(new Runnable(){
//            @Override
//            public void run() {
//            }
//        }).start();
        //这里的Lambda表达式省略了中间的那个Runnable
        new Thread(()->System.out.println("我爱你")).start();
        //与上面比较是不是很相近
        new WeddingCompany(new You()).happyMarry();
//        WeddingCompany weddingCompany = new WeddingCompany(you);
//        weddingCompany.happyMarry();
    }
}
//共同实现的接口
interface Marry{
    void happyMarry();
}
//真实对象,你去结婚
class You implements Marry{

    @Override
    public void happyMarry() {
        System.out.println("You准备结婚了");
    }
}
//代理对象,帮助你结婚
class WeddingCompany implements Marry{
    private Marry target;//真实对象
    public WeddingCompany(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("收尾款,完成婚礼");
    }

}

Guess you like

Origin blog.csdn.net/logtcm4/article/details/127329612#comments_27041755