多线程
3 静态代理
这里以一个现实生活中的例子来解释并实现所谓的静态代理模式,即结婚者雇用婚庆公司来帮助自己完成整个婚礼过程:
package com.duo.lambda;interface Marry {void HappyMarry();//人生四大乐事:久旱逢甘霖;他乡遇故知;洞房花烛夜;金榜题名时
}//结婚主人公
class Protagonist implements Marry {@Overridepublic void HappyMarry() {System.out.println("Protagonist开心地结婚了");}
}//代理婚庆公司
class WeddingCompany implements Marry {private final Marry target;public WeddingCompany(Marry target) {this.target = target;}@Overridepublic void HappyMarry() {before();this.target.HappyMarry();after();}private void before() {System.out.println("在结婚之前:布置婚礼现场");}private void after() {System.out.println("在结婚之后:收取剩余尾款");}
}public class StaticProxy {public static void main(String[] args) {WeddingCompany weddingCompany = new WeddingCompany(new Protagonist());weddingCompany.HappyMarry();}
}
运行结果:
此外,代码体public class StaticProxy {}
中的代码也可以写成:
public class StaticProxy {public static void main(String[] args) {Protagonist protagonist = new Protagonist();WeddingCompany weddingCompany = new WeddingCompany(protagonist);weddingCompany.HappyMarry();}
}
与之前所学的Thread线程进行对比,是为同理:
public class StaticProxy {public static void main(String[] args) {new Thread(() -> System.out.println("love")).start();new WeddingCompany(new Protagonist()).HappyMarry();}
}
【小结】静态代理模式:
- 真实对象和代理对象都要实现同一个接口
- 代理对象要代理真实角色
这样做的好处:代理对象可以做很多真实对象做不了的事情;而真实对象可以专注做自己的事情