设计模式(十)代理模式

来源:互联网 发布:方维o2o 6.0 源码 编辑:程序博客网 时间:2024/05/22 18:19

代理:只需要对象进行相关的操作,对象操作的前后的处理的行为人,即是代理。


代码之静态代理:

球员相关工作的接口:

public interface PlayerInterface {//踢球,球员本身的技能public void playFootBall();//下面为经纪人(代理的工作)public void chooseFootBallTeam();public void getAdvertisement();}

球员类实现其接口:

public class FootBallPlayer implements PlayerInterface{@Overridepublic void playFootBall() {System.out.println("驰骋足坛");}@Overridepublic void chooseFootBallTeam() {System.out.println("选择伟大的俱乐部发展");}@Overridepublic void getAdvertisement() {System.out.println("代言广告");}}

球员经纪人(代理)类实现接口:

public class PlayerProxy implements PlayerInterface{public PlayerProxy(PlayerInterface playerInterface) {super();this.playerInterface = playerInterface;}private PlayerInterface playerInterface;@Overridepublic void playFootBall() {playerInterface.playFootBall();}@Overridepublic void chooseFootBallTeam() {System.out.println("帮助球员选择伟大的俱乐部发展");}@Overridepublic 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;}@Overridepublic 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方法,故只打印了相关输出

驰骋足坛



原创粉丝点击