代理模式就是用一个第三者的身份去完成工作,其实际意义跟字面意思其实是一样的,理解方式有很多,还是例子直观.
本例的实现类是实现买票功能,实际应用想要添加身份验证功能,利用代理模式添加验证步骤.上例子:
package com.learn.proxy.proxyModel; /**
* 初始功能接口,买票
* @author garfield
*
*/
public interface Tickets {
public abstract void buy();
}
package com.learn.proxy.proxyModel; /**
* 真实实现购买票代码
* @author garfield
*
*/
public class RealBuy implements Tickets{ @Override
public void buy() {
System.out.println("pay money"); } }
package com.learn.proxy.proxyModel; /**
* 代理购买,由于需要在买票之前进行身份验证,所以增加代理功能
* @author garfield
*
*/
public class ProxyBuy implements Tickets{ private Tickets tickets; ProxyBuy(Tickets tickets) {
// TODO Auto-generated constructor stub
this.tickets = tickets;
} @Override
public void buy() {
getAuthority();
this.tickets.buy();
} public void getAuthority(){
System.out.println("get authority");
} }
package com.learn.proxy.proxyModel; /**
* 运行进行购买
* @author garfield
*
*/
public class BuyTickets {
public static void main(String[] args) {
new ProxyBuy(new RealBuy()).buy();
} }
运行结果:
get authority
pay money
done