设计模式(十)代理模式

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


代码之静态代理:

球员相关工作的接口:

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方法,故只打印了相关输出

驰骋足坛



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值