一、定義
代理模式給某一個對象提供一個代理對象,並由代理對象控制對源對象的引用。代理就是一個人或一個機構代表另一個人或者一個機構採取行動。某些情況下,客戶不想或者不能夠直接引用一個對象,代理對象可以在客戶和目標對象直接起到中介的作用。客戶端分辨不出代理主題對象與真實主題對象。代理模式可以並不知道真正的被代理對象,而僅僅持有一個被代理對象的接口,這時候代理對象不能夠創建被代理對象,被代理對象必須有系統的其他角色代爲創建並傳入。
二、分類
A、遠程代理:
爲一個對象在不同的地址空間提供局部代表,這樣可以隱藏一個對象存在於不同地址空間的事實。
B、虛擬代理
根據創建開銷很大的對象,通過它來存放實例化需要很長時間的對象。
C、安全代理
用來控制真是對象訪問時的權限。
D、智能指引
指當調用真實的對象時,代理處理另外一些事情。
三、結構圖
四、代碼示例
1、演示Action.java
/**
* 演示人物代理模式
* @author lattice
*
*/
public class Action {
public static void main(String[] args) {
Peter peter=new Peter();
peter.attatch();
//使用代理類,演示attatch mary
Lili lili=new Lili(new Mary());//lili help to get attach to Mary
lili.getAttach();
}
}
2、代理類Person.java
/**
* @use 代理模式,爲了解決Peter想通過Lili來找Maria和Mary玩。
* @author lattice
* @dete 2016-12-28
*/
public interface Person {
public void attatch();
}
class Peter implements Person {
@Override
public void attatch() {
System.out.println("this is Peter.I want "+
"to get attached to Mary or Maria.Can you help me?");
}
}
class Lili implements Person {// 代理類
Person person;
Lili(Person person) {
this.person = person;
System.out.println("Yes ,I'll help you,Peter,don't warry.");
}
public void getAttach() {
person.attatch();
}
@Override
public void attatch() {
person.attatch();
}
}
class Mary implements Person {// 其他實現類
@Override
public void attatch() {
System.out.println("this is Mary,hi,Peter.");
String str="111";
}
}
class Maria implements Person {// 其他實現類
@Override
public void attatch() {
System.out.println("this is Meria,hi,Peter.");
}
}