---
title: "代理设计模式"
author: "hm4123660"
date: "2015-05-27T18:29:02Z"
tags: ["Java", "invocationhandler", "代理模式", "动态代理模式", "静态代理模式"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2016-09-08T14:58:56Z"
id: 2214892
url: "https://longpo.iteye.com/blog/2214892"
---

代理设计模式（Proxy）主要为其他对象提供一种代理方式以控制对这个对象的访问，在某些情况下，一个对象不想或者不能直接引用另一个对象，而代理对象可以在客户端和目标对象之间起到中介的作用。代理模式的思想是为了提供额外的处理或者不同的操作而在实际对象与调用者之间插入一个代理对象。这些额外的操作通常需要与实际对象进行通信。

     其实代理说白一点就是真实对象的代表，在访问对象时引入一定程度的间接性，因为这些间接性可以附加多种用途。代理模式可分为静态代理和动态代理。

 

**1.静态代理模式**

       为了更形象的说明代理模式，使用相亲来进行举例。相亲中的媒婆就好比代理对象，需要媒婆从中协调和美言几句，而当事人就是被代理对象了。

 

首先要把事件主题抽象成接口，这里相亲当然就是主题了，定义相亲接口blind

```
interface blind{
		//定义相亲接口
		public void blinding();
	}
```

   

定义被代理对象（Person）

```
//被代理对象
class Man implements blind
{

	public String name;
	
	public Man(String name)
	{
		this.name=name;
	}
	@Override
	public void blinding() {
		System.out.println(name+" 正在相亲中。。。。。");
	}
	
}
```

  

定义代理对象（媒婆）

```
//代理对象
class matchmaker implements blind{

	private Man man;//被代理的对象需要确定
	
	public matchmaker(Man man)
	{
		this.man=man;
	}
	//相亲前
	public void before()
	{
		System.out.println("帮被代理对象美言几句。。。。");
	}	
	//相亲后
	public void after()
	{
		System.out.println("相亲成功。。。。。。。");
	}
	//相亲
	@Override
	public void blinding() {
		//相亲前
		before();
		man.blinding();
		//相亲后
		after();
	}
	
}
```

 

代理模式使用

```
public static void main(String[] args) {
		Man man=new Man("小明");
		//创建代理对象
		matchmaker ok=new matchmaker(man);		
		ok.blinding();
	}
```

 运行结果

![](http://dl2.iteye.com/upload/attachment/0108/9790/521031f0-032a-3b4c-b1a0-8c1ef9ab059b.png)  
 

       静态代理模式需要真实角色必须是事先已经存在的，并将其作为代理对象内部属性。这样在实际使用时，一个真实角色必须对应一个代理角色，会导致类的急剧膨胀。

 

**2.动态代理模式**

     静态代理模式里面被代理的类型需要提前确定，一个真实角色必须对应一个代理类，而然每个代理类只是里面的被代理对象不一样而已。

     使用动态代理可以解决这个问题，使用[java反射机制](/blog/2206858 "http://longpo.iteye.com/blog/2206858")来解决被代理对象的类型确定。

 

动态代理实现代码

```
package com.longpo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyProxy  {

	public static void main(String[] args) {
		
		Man man  = new Man("小明");
		  
		InvocationHandler handler = new matchmaker(man);
		  
		Class<?> classType = handler.getClass();
		  
		//使用反射生成代理对象	  
		blind ok = (blind)Proxy.newProxyInstance(classType.getClassLoader(),man.getClass().getInterfaces(),handler);
		 
		ok.blinding();

	}
		
}
interface blind{
	//定义相亲接口
	public void blinding();
}

//被代理对象
class Man implements blind
{

	public String name;
	
	public Man(String name)
	{
		this.name=name;
	}
	@Override
	public void blinding() {
		System.out.println(name+" 正在相亲中。。。。。");
	}
	
}

//代理对象
class matchmaker implements InvocationHandler{

	private Object object;//被代理的对象不确定
	
	public matchmaker(Object object)
	{
		this.object=object;		
	}
	//相亲前
	public void before()
	{
		System.out.println("帮被代理对象美言几句。。。。");
	}	
	//相亲后
	public void after()
	{
		System.out.println("相亲成功。。。。。。。");
	}
	//相亲
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		//相亲前
		before();
		//相亲中
		method.invoke(object, args);
		//相亲后
		after();
		return null;
	}
	
}
```

 运行结果：

![](http://dl2.iteye.com/upload/attachment/0108/9790/521031f0-032a-3b4c-b1a0-8c1ef9ab059b.png)  
 

 

     通过这种方式，被代理的对象可以在运行时动态改变，需要控制的接口可以在运行时改变，控制的方式也可以动态改变，从而实现了非常灵活的动态代理关系。

 

![](http://dl2.iteye.com/upload/attachment/0119/9167/901fc03f-126e-3146-bab6-80ede0bdca08.png)  
   
![](http://dl2.iteye.com/upload/attachment/0119/9169/c89ef85b-0b48-3dec-83d5-ccd8e3e7b492.png)