---
title: "proxy 的原理"
author: "dmwdmc"
date: "2013-06-13T14:24:15Z"
tags: []
categories: ["编程语言"]
slug: "proxy"
draft: false
lastmod: "2013-06-13T14:26:34Z"
id: 1886173
url: "https://dmwdmc.iteye.com/blog/1886173"
---

设计模式中proxy模式可以在jdk中的proxy得到体现。
它也是spring的核心思想。

首先我定义个ActionPrettyWomanInterface　接口。

```java
public interface ActionPrettyWomanInterface {
	void action();
}

```


针对于这个接口，我们可以有多个实现。
一个是帮助美女的实现。

```java
public class HelpPrettyWoman implements ActionPrettyWomanInterface{
	public void action() {
		System.out.println("我在帮美女补丝袜 .");
	}
}
```

另一个是玩美女。
public class PlayPrettyWoman implements ActionPrettyWomanInterface{
	public void action() {
		System.out.println("我在玩美女.");
	}
}


那么我们只是简单的玩，是不是太没情调了呢。
这时候我们就可以通过代理机制里的InvocationHandler加入一些情调。

```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class SexyInvocationHandler implements InvocationHandler{
	private Object prettyWoman;
	public SexyInvocationHandler(ActionPrettyWomanInterface prettyWoman){
		this.prettyWoman=prettyWoman;
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Object result=null;
		try{
			System.out.println(proxy.getClass().getSimpleName());
			System.out.println("让美女穿上丝袜，剪开档.");
			result =method.invoke(prettyWoman, args);
			System.out.println("抽跟烟~~~.");
		}catch(Exception e){
		}
		return result;
	}

}
```



之后我们就可以大玩特玩了。

```java
import java.lang.reflect.Proxy;
public class TestActionWithWoman {
	public static void main(String[] args) {
			ActionPrettyWomanInterface playWoman=new PlayPrettyWoman();
		ActionPrettyWomanInterface helpWoman=new HelpPrettyWoman();
		ActionPrettyWomanInterface fuckProxy=(ActionPrettyWomanInterface)Proxy.
		newProxyInstance(playWoman.getClass().getClassLoader(), playWoman.getClass().getInterfaces(), new SexyInvocationHandler(playWoman));
		fuckProxy.action();
		ActionPrettyWomanInterface remedyProxy=(ActionPrettyWomanInterface)Proxy.
		newProxyInstance(helpWoman.getClass().getClassLoader(), helpWoman.getClass().getInterfaces(), new SexyInvocationHandler(helpWoman));
		remedyProxy.action();
		System.out.println("fuckProxy classname:"+fuckProxy.getClass().getName());
	}
}
```


控制台输出：

> $Proxy0
> 让美女穿上丝袜，剪开档.
> 我在玩美女.
> 抽跟烟~~~.
> $Proxy0
> 让美女穿上丝袜，剪开档.
> 我在帮美女补丝袜 .
> 抽跟烟~~~.
> fuckProxy classname:$Proxy0


从中我们可以知道，当我们用代理机制创建关于接口或者类的对象时候，
它的对象实现是jdk产生的动态代理对象Proxy0。

当我们要调用玩美女或者帮助美女方法时候，　它的实际顺序是先调用InvocationHandler里的invoke，　然后invoke会通过反射调用玩美女或者帮助美女方法。


得出结论：如果我们不实现InvocationHandler的invoke方法，那么我们实际中的方法讲不会被调用到。所以这个类必须重写。

然后另外我们可以得知，创建对象除了new以后，还可以通过代理实现。