代理模式:為其他對象提供一種代理以控制對這個對象的訪問软棺。在某些情況下乖酬,一個對象不適合或者不能直接引用另一個對象肠缔,而代理對象可以在客戶端和目標(biāo)對象之間起到中介的作用,通過代理對象完成真是對象的某些功能闷旧。
代理分為靜態(tài)代理和動態(tài)代理:
-
靜態(tài)代理
- 首先創(chuàng)建一個業(yè)務(wù)接口(公司員工申請獎金的接口):
/**
*
* 作者: luweicheng24
* 時間: 2017年9月30日
* 功能描述: 公司員工申請獎金的業(yè)務(wù)接口
*
*/
public interface ApplyBonus {
void result();// 申請結(jié)果
}
- 創(chuàng)建一個員工類,實(shí)現(xiàn)申請獎金的業(yè)務(wù)接口:
/**
*
* 作者: luweicheng24
* 時間: 2017年9月30日
* 功能描述: 員工類
*
*/
public class Employee implements ApplyBonus {
public Employee(String position) {
this.position = position;
}
private int salary; //獎金薪水
private String position; // 職位
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public void result() {
System.out.println(position+"申請獎金的最后金額="+salary);
}
@Override
public String toString() {
return "Person [salary=" + salary + ", position=" + position + "]";
}
}
- 創(chuàng)建一個員工的代理類實(shí)現(xiàn)根據(jù)員工職位決定獎金:
/**
*
* 作者: luweicheng24
* 時間: 2017年9月30日
* 功能描述: 員工代理類
*
*/
public class EmployeeProxy implements ApplyBonus{
private int salary; // 代理獎金
private String position; // 代理對象的職位
private ApplyBonus employee; // 代理對象
/**
* 代理對象的構(gòu)造函數(shù)
* @param employee 員工對象
*/
public EmployeeProxy(Employee employee) {
this.employee = employee;
this.position = employee.getPosition();
}
@Override
public void result() {
switch (position) {
case "員工":
salary = 1000;
break;
case "主管":
salary = 2000;
break;
}
}
@Override
public String toString() {
return "代理信息 [獎金 =" + salary + ", 職位=" + position + "]";
}
}
員工代理類通過傳入代理對象钧唐,對代理對象的信息進(jìn)行核實(shí)和確認(rèn)之后合理分發(fā)獎金忙灼,靜態(tài)代理通常在開發(fā)中為了補(bǔ)充被代理對象的邏輯,以及在前期開發(fā)中未做的一下工作任務(wù)钝侠。
動態(tài)代理
在Java中存在一個類 Proxy该园,該類是專門用來生成代理對象,然后執(zhí)行代理方法等功能帅韧,該類通過一個靜態(tài)方法生成代理里初,下面筆者貼部分源碼加上自己的注釋:
/**
* loader : 需要代理對象的類加載器
* interfaces 表示該代理對象實(shí)現(xiàn)的接口的集合
* InvocationHandler :一個包含invoke方法的接口
* invoke方法是在代理對象每次調(diào)用被代理對象的方法的時候調(diào)用
*/
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
InvocationHandler
該類的原文注釋:
/**
* Processes a method invocation on a proxy instance and returns
* the result. This method will be invoked on an invocation handler
* when a method is invoked on a proxy instance that it is
* associated with.
*/
翻譯的意思:處理代理實(shí)例上的方法調(diào)用并返回 結(jié)果。
這個方法將在調(diào)用處理程序中被調(diào)用當(dāng)一個方法在代理實(shí)例上被調(diào)用時關(guān)聯(lián)忽舟。
該類只包含一個方法:
public interface InvocationHandler {
/**
* proxy :表示代理對象
* method: 表示代理的方法
* args : 表示方法的參數(shù)
* 該方法在被代理對象中的任何方法執(zhí)行時執(zhí)行
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
所以需要在調(diào)用被代理對象方法執(zhí)行時添加邏輯双妨,就需要實(shí)現(xiàn)該類的接口,在invoke方法中叮阅,添加邏輯斥难。
了解InvocationHandler之后,繼續(xù)看Proxy的newProxyInstance
方法帘饶,在該方法中主要包含三個方法:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
if (h == null) {
throw new NullPointerException();
}
/*
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass(loader, interfaces); // 1.通過類加載器和接口數(shù)組獲取代理類
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
/**
* constructorParams 表示InvocationHandler實(shí)現(xiàn)類的數(shù)組
* / ** parameter types of a proxy class constructor */
* private final static Class[] constructorParams =
* { InvocationHandler.class };
*/
Constructor cons = cl.getConstructor(constructorParams); // 2. 獲取代理類的構(gòu)造方法
return cons.newInstance(new Object[] { h }); // 3. 創(chuàng)建代理對象
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
} catch (IllegalAccessException e) {
throw new InternalError(e.toString());
} catch (InstantiationException e) {
throw new InternalError(e.toString());
} catch (InvocationTargetException e) {
throw new InternalError(e.toString());
}
}
對如上三個步驟解釋:
- Class<?> cl = getProxyClass(loader, interfaces); 獲取代理類,貼出源碼(省略了部分不重要的源碼),部分代碼添加注釋
public static Class<?> getProxyClass(ClassLoader loader,
Class<?>... interfaces)
throws IllegalArgumentException
{
if (interfaces.length > 65535) { // 接口數(shù)組長度不能超過65535
throw new IllegalArgumentException("interface limit exceeded");
}
Class<?> proxyClass = null; // 代理類的引用
/* collect interface names to use as key for proxy class cache */
String[] interfaceNames = new String[interfaces.length]; // 創(chuàng)建一個接口名組成的字符數(shù)組群扶,在之后的代理類的緩存鍵值對中作為Key及刻。
// for detecting duplicates
Set<Class<?>> interfaceSet = new HashSet<>(); // 創(chuàng)建一個set集合,存儲接口類
// 便利接口數(shù)組竞阐,存儲接口類到set中
for (int i = 0; i < interfaces.length; i++) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
String interfaceName = interfaces[i].getName();
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(interfaceName, false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != interfaces[i]) {
throw new IllegalArgumentException(
interfaces[i] + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.contains(interfaceClass)) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
interfaceSet.add(interfaceClass);
interfaceNames[i] = interfaceName;
}
// 將接口名數(shù)組轉(zhuǎn)換成一個L
List<String> key = Arrays.asList(interfaceNames);
/*
* Find or create the proxy class cache for the class loader.
*/
// 從loaderToCache一個弱引用的Map key是一個類加載器 value 是如下的cache集合缴饭,
// cache 是值為接口名字的list 值為 類加載器 如果緩存中沒有,添加到緩存
Map<List<String>, Object> cache;
synchronized (loaderToCache) {
cache = loaderToCache.get(loader);
if (cache == null) {
cache = new HashMap<>();
loaderToCache.put(loader, cache);
}
}
// 加鎖從緩存給代理類賦值
synchronized (cache) {
do {
Object value = cache.get(key);
if (value instanceof Reference) {
proxyClass = (Class<?>) ((Reference) value).get();
}
if (proxyClass != null) {
// proxy class already generated: return it
return proxyClass;
} else if (value == pendingGenerationMarker) {
// proxy class being generated: wait for it
try {
cache.wait();
} catch (InterruptedException e) {
}
continue;
} else {
cache.put(key, pendingGenerationMarker);
break;
}
} while (true);
}
// 查找代理的包名
try {
String proxyPkg = null; // package to define proxy class in
for (int i = 0; i < interfaces.length; i++) {
int flags = interfaces[i].getModifiers();
if (!Modifier.isPublic(flags)) {
String name = interfaces[i].getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) { // if no non-public proxy interfaces,
proxyPkg = ""; // use the unnamed package
}
{
/*
* Choose a name for the proxy class to generate.
*/
long num;
synchronized (nextUniqueNumberLock) {
num = nextUniqueNumber++;
}
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Verify that the class loader hasn't already
* defined a class with the chosen name.
*/
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces);
try {
proxyClass = defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
// add to set of all generated proxy classes, for isProxyClass
proxyClasses.put(proxyClass, null);
} finally {
synchronized (cache) {
if (proxyClass != null) {
cache.put(key, new WeakReference<Class<?>>(proxyClass));
} else {
cache.remove(key);
}
cache.notifyAll();// 喚醒等待的線程
}
}
return proxyClass;
}
- Constructor cons = cl.getConstructor(constructorParams);獲取代理類的構(gòu)造方法
- cons.newInstance(new Object[] { h });通過構(gòu)造方法創(chuàng)建一個實(shí)例骆莹。
好了颗搂,源碼分析完了,回到上面的問題幕垦,如何動態(tài)代理員工進(jìn)行獎金的分發(fā)丢氢,創(chuàng)建一個代理類實(shí)現(xiàn)InvocationHandler接口。
/*
* 代理處理類
*/
public class DynamicProxy implements InvocationHandler{
private Employee target;
public DynamicProxy(Employee target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
/*
* 代理類方法執(zhí)行時調(diào)用
*/
if(method.getName().equals("result")){
if(target.getPosition().equals("經(jīng)理")){
target.setSalary(target.getSalary()+1000);
}else {
target.setSalary(target.getSalary()+500);
}
}
Object obj = method.invoke(target, args);
/*
* 委托類方法執(zhí)行后操作
*/
return obj;
}
}
耗費(fèi)了好幾個小時了先改,下面來測試一下:
public class Proxytest {
public static void main(String[] args) {
ApplyBonus buyCar = (ApplyBonus)Proxy.newProxyInstance(Employee.class.getClassLoader(), new Class[]{ApplyBonus.class},new DynamicProxy(new Employee("經(jīng)理")));
buyCar.result();
}
}
控制臺輸出結(jié)果:
經(jīng)理申請獎金的最后金額=1000
以上均是個人的理解疚察,如有疑問留言討論。