您的位置:首页 > 其它

代理模式(Proxy Pattern)

2013-08-28 16:55 162 查看
代理模式:为另一个对象提供一个替身或占位符以控制对这个对象的访问

代理模式有很多变体,例如:

远程代理:控制访问远程对象(java RMI)

虚拟代理:控制访问创建开销大的对象

保护代理:基于权限控制对对象的访问

缓存代理:为开销大的运算结果提供暂时存储,也允许多个客户共享缓存结果,以降低计算、网络延迟

复杂隐藏代理:用来隐藏一个类的复杂集合的复杂度(和外观模式不同,外观模式只是提供了另一个接口)

代理模式的类图如下:



代理和实际对象继承自同一个接口,故代理可以在实际对象出现的地方代替实际对象

实际对象是真正做事的地方,但是代理控制着它的访问

代理持有对实际对象的引用,故在必要时可以将请求转发给实际对象



最基本的保护代理:



public interface Person {
	public String reply(String name);
}
public class BeforeProxy implements Person {
	private Person smith;
	
	public BeforeProxy(Person smith){
		this.smith = smith;
	}

	public String reply(String name) {
		if(name.length() >= 4){
			return smith.reply(name);
		}else{
			return "name length error!";
		}
	}
}
public class AfterProxy implements Person {
	private Person smith;
	
	public AfterProxy(Person smith){
		this.smith = smith;
	}
	
	public String reply(String name) {
		String result = smith.reply(name);
		System.out.println("after!");
		return result;
	}
}
public class Smith implements Person {
	public String reply(String name) {
		return "I will call you back soon!";
	}
}
public class Test {
	public static void main(String[] args) {
		Person smith = new Smith();
		BeforeProxy bp = new BeforeProxy(smith);
		AfterProxy ap = new AfterProxy(smith);
		System.out.println(bp.reply("12345"));
		System.out.println(ap.reply("12345"));
	}
}

运行结果为:

I will call you back soon!
after!
I will call you back soon!

有几个设计模式在功能上十分相似,在这里说明一下他们的区别:

策略模式:动态的赋予类不同的行为,并且一个类在同一时间只能有一个行为。这种行为是类的一部分。

装饰模式:通过不断的装饰,赋予类新的行为,这种装饰可以是多层的。装饰者和被装饰的类虽然继承于相同的父类,但是装饰者在某些时候并不是100%等同于被装饰者(有些方法对于装饰者来说是没有意义的)

代理模式:通过代理控制对实际对象的访问,可以像使用真实对象一样使用代理,代理===真实对象



当然代理模式不同变体之间,具体的实现方式差异非常大
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: