Spring2.5学习4.1_静态代理实现

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

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

HelloInterface接口

package proxy;

public interface HelloInterface {
	public void sayHello();
}

实现HelloInterface接口的类HelloInterfaceImpl

package proxy;

public class HelloInterfaceImpl implements HelloInterface {

	@Override
	public 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;
	}
	@Override
	public 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就是被代理的对象。


结果:


posted @ 2015-07-07 15:33  小鲜肉成长记  阅读(178)  评论(0编辑  收藏  举报