Java設計模式之-代理模式
其實每個模式名稱就表明了該模式的作用,代理模式就是多一個代理類出來,替原對象進行一些操作,比如我們在租房子的時候會去找中介,爲什麼呢?因爲你對該地區房屋的信息掌握的不夠全面,希望找一個更熟悉的人去幫你做,此處的代理就是這個意思。再如我們有的時候打官司,我們需要請律師,因爲律師在法律方面有專長,可以替我們進行操作,表達我們的想法。先來看看關係圖:
根據上文的闡述,代理模式就比較容易的理解了,我們看下代碼:
public class ProxyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Sourceable1 source1=new Proxy();
source1.method();
}
}
interface Sourceable1
{
public void method();
}
class Source1 implements Sourceable1
{
@Override
public void method() {
System.out.println("this is original method");
}
}
class Proxy implements Sourceable1
{
private Source1 source1;
public Proxy()
{
super();
this.source1=new Source1();
}
@Override
public void method() {
before();
source1.method();
after();
}
private void after() {
System.out.println("after proxy");
}
private void before() {
System.out.println("before proxy");
}
}
輸出結果:
before proxy
this is original method
after proxy
代理模式的應用場景:
如果已有的方法在使用的時候需要對原有的方法進行改進,此時有兩種辦法:
1、修改原有的方法來適應。這樣違反了“對擴展開放,對修改關閉”的原則。
2、就是採用一個代理類調用原有的方法,且對產生的結果進行控制。這種方法就是代理模式。
使用代理模式,可以將功能劃分的更加清晰,有助於後期維護!