静态代理模式
What
静态代理模式(Proxy Pattern),简单了说,就是代为处理。很多文章说代理模式像“中介”,可以这么理解,但举得例子,例如买车例子,就让我与装饰者模式混肴了。其实静态代理做的,就只有简单的转发对象或者提供其他逻辑功能。
也就是说,设计一个代理类,这个代理类能代理被代理类,并提供更多的服务。
注意:
1.代理也有可能是层层代理,也就是说,不止一个“中介”。
2.与装饰者模式区别:代理模式可以说是增加功能,装饰者模式是增强功能。类似于:超人用代理模式增加影身功能,超人用装饰者模式增强镭射眼威力。
How
假设有一个人,正在跑步,另外一个人给其记录跑步时间:
//测试类
public class Test {
public static void main(String []args) {
Human human = new Human();
Counter counter = new Counter(human);
counter.run();
}
}
interface Sport{
void run();
}
//运动员跑步
class Human implements Sport{
public void run(){
System.out.println("Human run");
}
}
//记录员记录
class Counter implements Sport{
private Sport sport;
public Counter ( Sport sport ){
this.sport = sport;
}
public void run(){
System.out.println("before run :" + System.currentTimeMillis());
sport.run();
System.out.println("after run :" + System.currentTimeMillis());
}
}
运行结果:
before run :1574750981807
Human run
after run :1574750981809
以上展示的就是一个简单的静态代理,上面说了,可能不止一个代理类。那么按照上面的例子,我们再加一个,运动员跑步前要体检,跑步后也要体检,代码:
//测试类
public class Test {
public static void main(String []args) {
Human human = new Human();
Counter counter = new Counter(human);
MedicalStaff ms = new MedicalStaff(counter);
ms.run();
}
}
interface Sport{
void run();
}
//运动员跑步
class Human implements Sport{
public void run(){
System.out.println("Human run");
}
}
//记录员记录跑步时间
class Counter implements Sport{
private Sport sport;
public Counter ( Sport sport ){
this.sport = sport;
}
public void run(){
System.out.println("before run :" + System.currentTimeMillis());
sport.run();
System.out.println("after run :" + System.currentTimeMillis());
}
}
//医务人员跑步体检
class MedicalStaff implements Sport{
private Sport sport;
public MedicalStaff( Sport sport ) {
this.sport = sport;
}
public void run(){
System.out.println("check body before run");
sport.run();
System.out.println("check body after run");
}
}
运行结果
check body before run
before run :1574751683180
Human run
after run :1574751683182
check body after run
注意:
1.静态代理模式用到了java多态的特性;
2.静态代理模式类与类之间是一种组合的方式;
3.上面Counter与MedicalStaff也可以调换位置,先计时再检查身体。。。。
4.注意Sport接口!!
接下来点一下静态代理与动态代理的区别:在动态代理中Counter与MedicalStaff这两个类是由JVM动态为我们创建
动态代理的实现,请自行百度,有很多大神献出了代码!感恩~
When & Where
静态代理要了解的不多,用的也比较简单,主要就是动态代理,动态代理可以实现AOP(面向切面编程),面向切面编程可以在不改动源代码的情况下,给某一个或某一类方法,添加日志/事务/性能等等额外功能。
说到这里,也点一下AOP的实现方式:
1:java实现:实现invocationHandle;
2:Spring AOP实现:实现MethodBeforeAdvice/AfterReturningAdvice/MethodInterceptor;
3:Spring Bean实现(基于XML配置);
4:AspectJ实现:Spring集成了AspectJ,很方便,用注解去开发;
5:CGLIB;
本文深入解析静态代理模式,通过实例展示了如何使用代理类为被代理类增加或提供服务,对比了代理模式与装饰者模式的区别,同时介绍了静态代理与动态代理的不同及应用场景。
1958

被折叠的 条评论
为什么被折叠?



