静态代理
java的设计模式的代理模式,就是静态代理
写在前面的话,静态代理的优点和缺点
优点:可以在不改变一个类的方法下,对这个类的方法进行增强
缺点:静态代理需要创建物理文件,在想实现多个静态代理的操作,就需要好多的物理文件,不太优良
实现案例:
Subject接口:抽象主题的接口,有一个方法
package cn.dawn.day08proxy;/** * Created by Dawn on 2018/3/6. */public interface Subject { public void request();}
RealSubject类:真实主题的类,实现上面的Subject接口,实现他的方法
package cn.dawn.day08proxy;/** * Created by Dawn on 2018/3/6. */public class RealSubject implements Subject { public void request() { System.out.println("request本身——————————————————————————————-"); }}
ProxySubject类:代理主题的类,同样实现Subject接口,里面有个Subject的接口的实例对象,他的get/set方法,还有新的方法,对真实主题进行静态的增强
package cn.dawn.day08proxy;/** * Created by Dawn on 2018/3/6. */public class ProxySubject implements Subject { Subject subject; public void request() { System.out.println("before"); subject.request(); System.out.println("after"); } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; }}
单测方法:
package cn.dawn.day08proxy;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Created by Dawn on 2018/3/3. */public class test20180306 { @Test /*di注解注入*/ public void t01(){ Subject realSubject=new RealSubject(); ProxySubject proxySubject=new ProxySubject(); proxySubject.setSubject(realSubject); proxySubject.request(); //realSubject.request(); }}