静态代理模式总结:真实对象和代理对象,都要实现同一个接口,代理对象要代理真实角色。好处:代理对象可以做很多真实对象做不了、或者冗余的事情,真实对象只要专注做自己的事情就行。这种思想在多线程里面是一样的。语句如下:
new WeddingCompany(new You()).HappyMarry();
和
new Thread(new Runnable() { @Override public void run() { } }).start();
静态代理模式:
1 package com.huolongluo.coindemo.morethread.sub1; 2 3 /** 4 * Created by 火龙裸 on 2019/11/9. 5 * desc : 静态代理模式 6 * version: 1.0 7 */ 8 public class StatciProxy { 9 public static void main(String[] args) { 10 /*You you = new You();//你要结婚 11 WeddingCompany weddingCompany = new WeddingCompany(you); 12 weddingCompany.HappyMarry();*/ 13 14 new WeddingCompany(new You()).HappyMarry(); 15 } 16 } 17 18 interface Marry { 19 //人间四大喜事 20 //久旱逢甘霖 21 //他乡遇故知 22 //洞房花烛夜 23 //金榜题名时 24 25 void HappyMarry(); 26 } 27 28 //真实角色,你去结婚 29 class You implements Marry { 30 @Override 31 public void HappyMarry() { 32 System.out.println("要结婚了,超开心"); 33 } 34 } 35 36 //代理角色,婚庆公司帮助你结婚 37 class WeddingCompany implements Marry { 38 39 //代理谁--》真实目标角色 40 private Marry target; 41 42 public WeddingCompany(Marry target) { 43 this.target = target; 44 } 45 46 @Override 47 public void HappyMarry() { 48 before(); 49 this.target.HappyMarry();//“this.target”这就是真实对象 50 after(); 51 } 52 53 private void before() { 54 System.out.println("结婚之前,布置现场"); 55 } 56 57 private void after() { 58 System.out.println("结婚之后,收尾款"); 59 } 60 }