案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| public class StaticProxy { }
interface Marry{
void HappyMarry();
}
class You implements Marry{
@Override public void HappyMarry() { System.out.println("我要结婚了!,超开心"); }
}
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("结婚之后"); }
public static void main(String[] args) {
new Thread(()-> System.out.println("我爱你")).start();
WeddingCompany weddingCompany = new WeddingCompany(new You()); weddingCompany.HappyMarry();
}
}
|
总结
目标对象和代理对象都要实现同一个接口
代理对象要代理真实角色