对象身上的事太多,可以通过代理转移部分职责。可以减少冗余。
对象有什么方法想被代理,代理就要有对应方法。
通过接口实现
public class test {
public static void main(String[] args) {
BigStar s = new BigStar("杨超越");
Star starProxy = ProxyUtil.createProxy(s);
String rs = starProxy.sing("好日子");
System.out.println(rs);
starProxy.dance();
}
}
对象
public class BigStar {
private String name;
public BigStar(String name) {
this.name = name;
}
public String sing(String name) {
System.out.println(this.name + " 正在唱: " + name);
return "谢谢!谢谢!";
}
public void dance() {
System.out.println(this.name + " 正在优美的跳舞~~");
}
}
代理人
public interface Star {
String sing(String name);
void dance();
}
代理执行
package com.lzk.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyUtil {
public static Star createProxy(BigStar bigStar) {
/* Proxy.newProxyInstance
* 使用动态代理创建一个代理对象。
* 参数1: 用于指定一个类加载器
* 参数2: 指定生成的代理类和接口,也就是代理对象将要实现的接口
* 参数3: 用来指定该类的代理要做什么事情
*/
Star starProxy = (Star) Proxy.newProxyInstance(
ProxyUtil.class.getClassLoader(),
new Class[]{Star.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 代理对象要做的事情,可以在这里写代码
if (method.getName().equals("sing")) {
System.out.println("准备话筒,收费20万");
} else if (method.getName().equals("dance")) {
System.out.println("准备场地,收费1000万");
}
return method.invoke(bigStar, args); // 调用目标对象的方法
}
}
);
return starProxy; // 返回代理对象
}
}