Java 代理模式

代理 proxy模式,通过其他方式对目标用户进行访问,而不是直接访问目标用户,这样做的好处是:可以增加目标用户其他的功能呢

使用场景:如果想要一个方法代码加上自己的一些方法,但又不想改变这个方法,就可以使用代理模式

代理模式的关键在于:代理是目标对象的扩展,且可以调用目标用户

interface Action{public void work();}  //定义接口

定义代理类

class Proxy implements Action{
    private Action action;
    public Proxy(Action action) {this.action=action;}
    //扩展代理自己的方法
    public void begin() {System.out.println("订票");}
    public void end() {System.out.println("收尾");}
    public void work() { //覆写接口的方法
        this.begin();
        this.action.work(); //调用目标对象的方法
        this.end();
    }
}

测试

public class Text{
    public static void main(String[] args) {
        new Proxy(new Action() { //使用匿名内部类减少类文件
            public void work() {System.out.println("目标对象的方法:谈业务");}
        }).work();
    }
}

结果

 

posted @ 2018-01-05 21:15  沃泽法克  阅读(127)  评论(0)    收藏  举报