Spring2.5学习4.1

阅读: 评论:0

Spring2.5学习4.1

Spring2.5学习4.1

在静态代理中代理对象与被代理对象(目标对象)必须实现同一个接口,完整保留被代理对象的接口样式,也将接口不变的原则一直保留。

下面通过一个简单的示例来说明:

HelloInterface接口

package proxy;public interface HelloInterface {public void sayHello();
}

实现 HelloInterface接口的类HelloInterfaceImpl

package proxy;public class HelloInterfaceImpl implements HelloInterface {@Overridepublic void sayHello() {System.out.println("Hello xianjj");}}

用于增强实现类HelloInterfaceImpl功能的类(代理)proTest

package proxy;public class ProTest implements HelloInterface {HelloInterface helloInterface;public ProTest(HelloInterface helloInterface) {super();this.helloInterface = helloInterface;}@Overridepublic void sayHello() {System.out.println("准备");helloInterface.sayHello();System.out.println("结束");}public static void main(String[] args) {HelloInterface pro = new proTest(new HelloInterfaceImpl());pro.sayHello();}
}

ProTest类实现了HelloInterface接口,并且构造方法的参数类型也是HelloInterface,这样ProTest具有实例变量helloInterface,这样就知道代理类的具体实现了,主要是使用proTest类对HelloInterfaceImpl的功能进行“包装”;最后通过main方法进行输出,结果如下截图。

在不改变原有类HelloInterfaceImpl的基础上对其进行功能性增强,在Hello xianjj的前后分别输出“准备”,‘结束’字样,这就是一个典型的日志或事务的AOP功能模型。从这里可以看到静态代理类自身的主要缺点,即扩展性不好,如果想代理更多的类,就需要创建更多的代理类。

在本例中proTest是代理类,HelloInterfaceImpl就是被代理的对象。


结果:


转载于:.html

本文发布于:2024-01-29 13:00:41,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170650444515464.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23