代理:只需要對象進行相關的操作,對象操作的前後的處理的行爲人,即是代理。
代碼之靜態代理:
球員相關工作的接口:
public interface PlayerInterface {
//踢球,球員本身的技能
public void playFootBall();
//下面爲經紀人(代理的工作)
public void chooseFootBallTeam();
public void getAdvertisement();
}
球員類實現其接口:
public class FootBallPlayer implements PlayerInterface{
@Override
public void playFootBall() {
System.out.println("馳騁足壇");
}
@Override
public void chooseFootBallTeam() {
System.out.println("選擇偉大的俱樂部發展");
}
@Override
public void getAdvertisement() {
System.out.println("代言廣告");
}
}
球員經紀人(代理)類實現接口:
public class PlayerProxy implements PlayerInterface{
public PlayerProxy(PlayerInterface playerInterface) {
super();
this.playerInterface = playerInterface;
}
private PlayerInterface playerInterface;
@Override
public void playFootBall() {
playerInterface.playFootBall();
}
@Override
public void chooseFootBallTeam() {
System.out.println("幫助球員選擇偉大的俱樂部發展");
}
@Override
public void getAdvertisement() {
System.out.println("幫助球員承接廣告");
}
}
測試代碼:
public class Test {
public static void main(String[] args) {
PlayerInterface footBallPlayer = new FootBallPlayer();
PlayerInterface playerProxy = new PlayerProxy(footBallPlayer);
playerProxy.playFootBall();
playerProxy.chooseFootBallTeam();
playerProxy.getAdvertisement();
}
}
輸出內容如下:
馳騁足壇
幫助球員選擇偉大的俱樂部發展
幫助球員承接廣告
代碼之動態代理:實現InvocationHandler接口
public class PlayerHandler implements InvocationHandler {
private PlayerInterface playerInterface;
public PlayerHandler(PlayerInterface playerInterface) {
super();
this.playerInterface = playerInterface;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//進行方法的篩選
if(method.getName().equals("playFootBall")){
method.invoke(playerInterface, args);
}
return null;
}
}
測試:
public static void main(String[] args) {
PlayerInterface footBallPlayer = new FootBallPlayer();
PlayerHandler handler = new PlayerHandler(footBallPlayer);
PlayerInterface proxy = (PlayerInterface) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{PlayerInterface.class}, handler);
proxy.playFootBall();
proxy.chooseFootBallTeam();
proxy.getAdvertisement();
}
控制檯輸出:因爲只處理了playFootBall方法,故只打印了相關輸出
馳騁足壇