五、代理模式proxy

一、定义

代理模式给某一个对象提供一个代理对象,并由代理对象控制对源对象的引用。代理就是一个人或一个机构代表另一个人或者一个机构采取行动。某些情况下,客户不想或者不能够直接引用一个对象,代理对象可以在客户和目标对象直接起到中介的作用。客户端分辨不出代理主题对象与真实主题对象。代理模式可以并不知道真正的被代理对象,而仅仅持有一个被代理对象的接口,这时候代理对象不能够创建被代理对象,被代理对象必须有系统的其他角色代为创建并传入。 

二、分类

A、远程代理:

为一个对象在不同的地址空间提供局部代表,这样可以隐藏一个对象存在于不同地址空间的事实。

B、虚拟代理

根据创建开销很大的对象,通过它来存放实例化需要很长时间的对象。

C、安全代理

用来控制真是对象访问时的权限。

D、智能指引

指当调用真实的对象时,代理处理另外一些事情。


三、结构图


四、代码示例

1、演示Action.java

/**
 * 演示人物代理模式
 * @author lattice
 *
 */
public class Action {

	public static void main(String[] args) {
		Peter peter=new Peter();
		peter.attatch();
		//使用代理类,演示attatch mary
		Lili lili=new Lili(new Mary());//lili help to get attach to Mary
		lili.getAttach();
	}
}


2、代理类Person.java

/**
 * @use 代理模式,为了解决Peter想通过Lili来找Maria和Mary玩。
 * @author lattice
 * @dete 2016-12-28
 */
public interface Person {
	public void attatch();
}

class Peter implements Person {
	@Override
	public void attatch() {
		System.out.println("this is Peter.I want "+
					"to get attached to Mary or Maria.Can you help me?");

	}
}

class Lili implements Person {// 代理类
	Person person;

	Lili(Person person) {
		this.person = person;
		System.out.println("Yes ,I'll help you,Peter,don't warry.");
	}

	public void getAttach() {
		person.attatch();
	}

	@Override
	public void attatch() {
		person.attatch();

	}
}

class Mary implements Person {// 其他实现类
	@Override
	public void attatch() {
		System.out.println("this is Mary,hi,Peter.");
		String str="111";

	}
}

class Maria implements Person {// 其他实现类
	@Override
	public void attatch() {
		System.out.println("this is Meria,hi,Peter.");

	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章