现在的位置: 首页 > 综合 > 正文

静态代理

2013年12月10日 ⁄ 综合 ⁄ 共 795字 ⁄ 字号 评论关闭
 

这是一个简单的静态代理的例子:

首先定义接口Ihello

public interface IHello {

    void sayHello(String msg);

}

再给出一个这个接口的简单实现类HelloSpker

public class HelloSpker implements IHello {

    public void sayHello(String msg) {

       System.out.println("this is HelloSpker and Hello "+msg);

    }

}

接下来给出Ihello接口的静态代理。要对Ihello进行代理,必须拥有Ihello接口的功能,即需要实现Ihello接口。

public class HelloProxy implements IHello {

    private IHello hello;

    public HelloProxy(IHello hello){

       this.hello = hello;

    }

    public void sayHello(String msg) {

       System.out.println("do proxy's things");

       hello.sayHello(msg);

    }

}

最后给出测试类:

public static void main(String[] args) {

       HelloProxy proxy = new HelloProxy(new HelloSpker());

       proxy.sayHello("staticproxy");

}

输出结果为:

do proxy's things

this is HelloSpker and Hello staticproxy

总结:静态代理实现简单,但是功能单一,自由度低。代理对象的一个接口只服务于一种类型的对象。在本例中HelloProxy代理只能服务于IHello类型的对象。

抱歉!评论已关闭.