1 package proxy.staticproxy; 2 3 public interface IStar { 4 5 public void sing(); 6 }
1 package proxy.staticproxy; 2 3 public class RealStar implements IStar{ 4 @Override 5 public void sing() { 6 System.out.println("我是大明星:我要大聲唱:巴拉巴拉。。。"); 7 } 8 }
1 package proxy.staticproxy; 2 3 public class ProxyStar implements IStar { 4 5 private IStar realStar; 6 7 public IStar proxy(IStar realStar){ 8 this.realStar = realStar; 9 return this; 10 } 11 12 13 @Override 14 public void sing() { 15 16 System.out.println("我是代理人:大明星唱歌開始前,我先宣傳一下:巴拉巴拉。。。"); 17 18 this.realStar.sing(); 19 20 System.out.println("我是代理人:大明星唱歌完畢了,我來總結一下:巴拉巴拉。。。"); 21 } 22 }
1 package proxy.staticproxy; 2 3 public class Test { 4 5 /** 6 * 7 * 靜態代理可以分爲兩類,以“代理人”和“大明星”爲例。 8 * 下面測試的爲基於相同接口的代理,代理人和大明星都是實現的相同接口 9 * 代理人實例內部維護(組合)大明星實例 10 * 對外暴露代理人的行爲 11 * 另一類是基於繼承的代理,假如大明星本身就沒有實現任何接口 12 * 那麼,代理人可以通過繼承大明星,覆寫大明星的方法(除final修飾的方法,wait方法,notify方法)、 13 * 達到代理大明星的邏輯 14 * @param args 15 */ 16 public static void main(String[] args) { 17 IStar star = new ProxyStar().proxy(new RealStar()); 18 star.sing(); 19 } 20 }