代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候会去找中介,为什么呢?
因为你对该地区房屋的信息掌握的不够全面,希望找一个更熟悉的人去帮你做,此处的代理就是这个意思。
再如我们有的时候打官司,我们需要请律师,因为律师在法律方面有专长,可以替我们进行操作,表达我们的想法。
例子:
//公共接口
public interface Sourceable {
public void method();
}
//目标类/被代理类
public class Source implements Sourceable {
public void method() {
System.out.println("the original method!");
}
}
//代理类
public class Proxy implements Sourceable {
private Source source;
public Proxy(Source source){
this.source = source;
}
public void method() {
before();
source.method();
atfer();
}
private void atfer() {
System.out.println("after proxy!");
}
private void before() {
System.out.println("before proxy!");
}
}
//测试类
public class ProxyTest {
public static void main(String[] args) {
Source target = new Source();
Sourceable proxy = new Proxy(target);
proxy.method();
}
}
代理模式的应用场景:
如果已有的方法在使用的时候需要对原有的方法进行改进,此时有两种办法:
1、修改原有的方法来适应。这样违反了“对扩展开放,对修改关闭”的原则。
2、就是采用一个代理类调用原有的方法,且对产生的结果进行控制。这种方法就是代理模式。
使用代理模式,可以将功能划分的更加清晰,有助于后期维护!
注意: 装饰模式和代理模式在很多情况下,大部分代码都是类似的,但是这俩种设计的意图是不一样的,装饰模式是增强被包装对象的功能,代理模式是控制被代理对象的行为
例如一块代码,如果被描述为使用了装饰模式,那么我们就知道设计的意图是增加被包装对象的功能,如果被描述为使用了代理模式,那么我们就知道设计的意图是控制被代理对象的行为,虽然这俩种情况下他们的代码结构基本相同.
代理类可分为两种:
静态代理类:
由程序员创建或由特定工具自动生成源代码,再对其编译。在程序运行前,代理类的.class文件就已经存在了。
动态代理类:在程序运行时,运用反射机制动态创建而成。
与静态代理类对照的是动态代理类,动态代理类的字节码在程序运行时由Java反射机制动态生成,无需程序员手工编写它的源代码。动态代理类不仅简化了编程工作,而且提高了软件系统的可扩展性,因为Java 反射机制可以生成任意类型的动态代理类。java.lang.reflect 包下面的Proxy类和InvocationHandler 接口提供了生成动态代理类的能力。
CGLib代理(第三方类库)
JDK实现动态代理需要实现类通过接口定义业务方法,对于没有接口的类,如何实现动态代理呢,这就需要CGLib了。CGLib 采用了非常底层的字节码技术,其原理是通过字节码技术为目标对象创建一个子类对象,并在子类对象中拦截所有父类方法的调用,然后在方法调用前后调用后都可以加入自己想要执行的代码。
需要这种方法只是需要俩个第三方jar包: cglib-3.2.1.jar和asm-5.0.4.jar
同时很多框架已经把这些jar包整合到一起了,比如spring框架的spring-core-3.2.4.RELEASE.jar,这一个jar包就包括上述俩个jar包的大多数功能
静态代理: staticProxy
例子:
//公共接口
public interface HelloService {
void sayHello();
}
//委托类
public class HelloServiceImpl implements HelloService{
public void sayHello() {
System.out.println("hello world");
}
}
//代理类
public class HelloServiceProxy implements HelloService{
private HelloService target;
public HelloServiceProxy(HelloService target) {
this.target = target;
}
public void sayHello() {
System.out.println("log:sayHello马上要执行了...");
target.sayHello();
}
}
//测试类
public class Test {
public static void main(String[] args) {
//目标对象
HelloService target = new HelloServiceImpl();
//代理对象
HelloService proxy = new HelloServiceProxy(target);
proxy.sayHello();
}
}
JDK的动态代理: dynamicProxy
例子:
//Student类
public class Student {
private long id;
private String name;
private int age;
get/set方法;
}
//日志类
public class StudentLogger {
public void log(String msg){
System.out.println("log: "+msg);
}
}
//Service接口 处理学生的相关业务
public interface IStudentService {
void save(Student s);
void delete(long id);
Student find(long id);
}
//接口的一个简单实现
public class StudentServiceImpl implements IStudentService {
public void delete(long id) {
System.out.println("student is deleted...");
}
public Student find(long id) {
System.out.println("student is found...");
return null;
}
public void save(Student s) {
System.out.println("student is saved...");
}
}
//InvocationHandler接口的实现类
//JDK动态代理中必须用到的接口实现
public class MyHandler implements InvocationHandler{
private Object target;
private StudentLogger logger = new StudentLogger();
public MyHandler(Object target, StudentLogger logger) {
this.target = target;
this.logger = logger;
}
public MyHandler(Object target) {
this.target = target;
}
//参数1 proxy 将来给目标对象所动态产生的代理对象
//参数2 method 将来你所调用的目标对象中的方法的镜像
//参数3 args 将来你所调用方法的时候所传的参数
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String msg = method.getName()+"方法被调用了...";
logger.log(msg);
Object o = method.invoke(target, args);
return o;
}
}
//测试类
public class DProxyTest {
public static void main(String[] args) {
IStudentService target = new StudentServiceImpl();
ClassLoader loader = target.getClass().getClassLoader();
Class<?>[] interfaces = target.getClass().getInterfaces();
InvocationHandler h = new MyHandler(target);
//参数1 loader 目标对象的类加载器
//参数2 interfaces 目标对象所实现的接口
//参数3 h InvocationHandler接口的实现类对象
IStudentService proxy = (IStudentService)Proxy.newProxyInstance(loader, interfaces, h);
proxy.delete(1);
proxy.save(null);
proxy.find(1);
System.out.println(proxy.toString());
System.out.println(proxy.getClass());
System.out.println(target.getClass());
}
}
第三方jar包提供的动态代理(cglib) CglibProxy
例子:
//目标的对象 没有实现接口
public class BookService {
public void addBook() {
System.out.println("添加书籍成功");
}
}
//产生代理对象的工厂类
public class MyCglibProxyFactory implements MethodInterceptor {
public Object getInstance(Class<?> c) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(c);
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("开始执行方法");
//这句代码最终会执行到我们目标对象中的方法
proxy.invokeSuper(obj, args);
System.out.println("方法执行结束");
return null;
}
}
//测试类
public class TestCglibProxy {
public static void main(String[] args) {
MyCglibProxyFactory cglib=new MyCglibProxyFactory();
BookService bookCglib= (BookService)cglib.getInstance(new BookService().getClass());
bookCglib.addBook();
System.out.println(bookCglib.getClass());
}
}
文章要用到的jar包:点击这里