设计模式笔记之六代理模式

代理模式

为什么需要代理模式

当我们需要访问外部资源的时候,由于我们自己网络限制,我们不能够访问到外部资源,但是如果有一个主机,可以我们访问外部的资源,然后将外部资源存放到存储设备上,然后我们可以访问这个存储设备来获取我们想要的资源。在这里这个主机扮演者代理的角色,帮助我们获取我们需要的资源,因此,我们需要代理模式来帮助我们实现我们自身不能实现的需求。

什么是代理模式

给某一个对象提供一个代理,并由代理对象控制对原对象的引用。

核心思想

通过代理类返回需要的资源,代理类是真实需求和目标资源的连通枢纽。

具体案例

模拟使用代理访问外部资源

UML:

设计模式笔记之六代理模式

代码

package com.dong.proxy;

public interface AccessResource {
	public void request(String url);
	public void response(float id);
}

package com.dong.proxy;

public class localhost implements AccessResource{

	@Override
	public void request(String url) {
		System.out.println("发送请求到" + url);
	}

	@Override
	public void response(float id ) {
		System.out.println("已经获得资源 ,编号为" + id);
	}
	
}

package com.dong.proxy;

import java.util.Random;

public class Proxy implements AccessResource{
	
	private localhost local;
	
	Random random = new Random();
	float str = random.nextFloat();
	
	public Proxy(localhost local) {
		super();
		this.local = local;
	}
	
	@Override
	public void request(String url) {
		local.request("proxy host");
		System.out.println("proxy host start access the "+ url);
		System.out.println("proxy Host Access the  " + url+ "  and store the resource");
		System.out.println("localhost  Start access proxy host  resource");
		System.out.println("Access end !!!" );
		
		this.response(str);
	}

	@Override
	public void response(float id) {
	
		System.out.println("return the resouce , 编号" + id );
		local.response(id);
	}
}

package com.dong.proxy;
/**
 * 运行结果:
 *  发送请求到proxy host
	proxy host start access the www.google.com
	proxy Host Access the  www.google.com  and store the resource
	localhost  Start access proxy host  resource
	Access end !!!
	return the resouce , 编号0.69638914
	已经获得资源 ,编号为0.69638914
 * @author liuD
 *
 */
public class client {
	public static void main(String[] args) {
		localhost host =new localhost();
		Proxy proxy = new Proxy(host);
		proxy.request("www.google.com");
	}
}


优点

简单,方便,直接,

扩展方便,当我们使用代理,不可以一步得到我们需要的结果,我们可以使用多个代理来实现我们需要的结果。

对于原始的请求到达一定的保密机制。

缺点

过于依赖代理角色。