代理:只需要对象进行相关的操作,对象操作的前后的处理的行为人,即是代理。
代码之静态代理:
球员相关工作的接口:
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方法,故只打印了相关输出
驰骋足坛