java設計模式學習,java設計模式

來源:互聯網
上載者:User

java設計模式學習,java設計模式

代理模式(Proxy)


其實每個模式名稱就表明了該模式的作用,代理模式就是多一個代理類出來,替原對象進行一些操作,比如我們在租房子的時候回去找中介,為什麼呢?因為你對該地區房屋的資訊掌握的不夠全面,希望找一個更熟悉的人去幫你做,此處的代理就是這個意思。再如我們有的時候打官司,我們需要請律師,因為律師在法律方面有專長,可以替我們進行操作,表達我們的想法。先來看看關係圖:

 

根據上文的闡述,代理模式就比較容易的理解了,我們看下代碼:

public interface Sourceable {      public void method();  }  public class Source implements Sourceable {        @Override      public void method() {          System.out.println("the original method!");      }  }  public class Proxy implements Sourceable {        private Source source;      public Proxy(){          super();          this.source = new Source();      }      @Override      public void method() {          before();          source.method();          atfer();      }      private void atfer() {          System.out.println("after proxy!");      }      private void before() {          System.out.println("before proxy!");      }  }  


測試:

public class ProxyTest {        public static void main(String[] args) {          Sourceable source = new Proxy();          source.method();      }  }



輸出:

before proxy!
the original method!
after proxy!


代理模式的應用情境:

如果已有的方法在使用的時候需要對原有的方法進行改進,此時有兩種辦法:

1、修改原有的方法來適應。這樣違反了“對擴充開放,對修改關閉”的原則。

2、就是採用一個代理類調用原有的方法,且對產生的結果進行控制。這種方法就是代理模式。

使用代理模式,可以將功能劃分的更加清晰,有助於後期維護!



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.