十、静态代理
对比:
new WeddingCompany(new You()).HappyMarry(); new Thread(()->{System.out.println("我爱你");}).start();
静态代理总结:
- 真实对象和代理对象需要实现同一个接口
- 代理对象需要代理真是角色
静态代理好处:
- 代理对象可以实现真实对象做不了的事情
- 真实对象可以专注自己的事情
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("你结婚了"); } }