十、静态代理

对比:

new WeddingCompany(new You()).HappyMarry();
new Thread(()->{System.out.println("我爱你");}).start();

静态代理总结:

  1. 真实对象和代理对象需要实现同一个接口
  2. 代理对象需要代理真是角色

静态代理好处:

  1. 代理对象可以实现真实对象做不了的事情
  2. 真实对象可以专注自己的事情

 

public class StaticProxy {

    public static void main(String[] args) {
        //原来:
        You you = new You();
        WeddingCompany weddingCompany = new WeddingCompany(you);
        weddingCompany.HappyMarry();

        //现在:
        new WeddingCompany(new You()).HappyMarry();

        //对比:
        new Thread(()->{System.out.println("我爱你");}).start();
    }
}

interface Marry{
    void HappyMarry();
}


class WeddingCompany implements Marry{

    //代理目标
    private Marry target;

    public WeddingCompany(Marry target) {
        //真实对象
        this.target = target;
    }

    @Override
    public void HappyMarry() {
        before();
        //真实对象
        target.HappyMarry();
        after();
    }

    private void before() {
        System.out.println("结婚前:布置现场");
    }
    private void after() {
        System.out.println("结婚后:收拾现场");
    }
}


class You implements Marry{

    @Override
    public void HappyMarry() {
        System.out.println("你结婚了");
    }
}

 

posted @ 2022-05-14 03:35  Epiphany8Z  阅读(21)  评论(0编辑  收藏  举报