0
点赞
收藏
分享

微信扫一扫

设计模式之代理模式精讲

沪钢木子 03-30 15:00 阅读 2

代理模式(Proxy Pattern)也叫委托模式,是一个使用率非常高的模式,比如我们在Spring中经常使用的AOP(面向切面编程)。

概念:为其他对象提供一种代理以控制对这个对象的访问。

代理类和实际的主题类都实现同一个接口,由代理类代替主题类去做一些操作,并且在操作的基础上,增加一些额外的操作。

下面我们以代理买房的例子,来帮助大家理解代理模式的使用。

public interface BuyHouse {
    void buy();
}

public class RealBuyer implements BuyHouse {
    @Override
    public void buy() {
        System.out.println("真正的买家,付钱买房。");
    }
}

public class EstateAgent implements BuyHouse {
    private RealBuyer realBuyer;
    public EstateAgent(RealBuyer realBuyer) {
        this.realBuyer = realBuyer;
    }
    @Override
    public void buy() {
        beforeBuy();
        realBuyer.buy();
        afterBuy();
    }
    private void beforeBuy() {
        System.out.println("挑选房子、谈价格等");
    }
    private void afterBuy() {
        System.out.println("交房、售后服务等");
    }
}

public class Demo {
    public static void main(String[] args) {
        EstateAgent estateAgent = new EstateAgent(new RealBuyer());
        estateAgent.buy();
    }
}

大家如果用过AOP,应该对这个实现非常眼熟。实际开发中,实现类如果是一个API,我们可以在代理类中进行很多操作。比如,增加权限校验,增加日志记录等。好处是非常明显的,整个过程我们没有改动已有的API,只是在代理类中对已有操作进行重新组合。AOP面向切面编程,也是非常形象的表达。

如果大家需要视频版本的讲解,大家可以关注我的B站:

七、设计模式之代理模式精讲

举报

相关推荐

0 条评论