本文由老王出租房子引出——代理设计模式,将从最简单的静态代理实现开始,后延伸使用jdk实现动态代理,最后扩展到Cglib实现动态代理。为了更深入理解代理模式,我们会对实际应用中的典型案例进行介绍,包括在Spring和Mybatis中的应用。
一、引出问题
在上一篇文章中,虽然老王和小王之间的电脑组装完美结束,但老王和小王之间的争吵并没有结束。老王决定把小王赶出去,把小王住的房子租出去。租金是用来支付游戏书的费用的。
[En]
In the last article, although the computer assembly between Lao Wang and Xiao Wang ended perfectly, the quarrel between Lao Wang and Xiao Wang did not end. Lao Wang decided to kick Xiao Wang out and rent out the house where Xiao Wang lived. The rent was used to cover the cost of the game book.
老王费尽心思摸清了各租房平台的规则,发布了房源信息,随后邻居提醒他:把房子租出去并不意味着躺着收房租,有一天租客提出了一些附加要求,在合同范围内,你也要尽量满足(为了了解,当然现实并不存在),房子租出去后,还要跟物业协调。
[En]
Lao Wang spent a lot of effort to figure out the rules of various rental platforms and released housing information, and then the neighbor reminded him: renting out the house does not mean lying down to collect rent, one day the tenant put forward some additional requirements, within the scope of the contract, you should also try to meet them (in order to understand, of course, reality does not exist), after the house is rented out, you have to coordinate with the property.
老王开始思考,如果我直租给租客,会面临两个问题:
①我需要了解租房的整个过程。我自己的生意和租房之间存在严重的耦合。
[En]
① I need to understand the whole process of renting. There is a serious coupling between my own business and renting.
我不得不参与②租户提出的一些要求,我不得不改变自己的日程安排。
[En]
I had to get involved in some of the demands made by ② tenants, and I had to change my own schedule.
我应该想到一种办法,
第一点是将业务与功能解耦,业务层专注于业务,比如网络接口请求。业务层只需要知道调用哪个接口请求方法,而不需要知道如何发起接口请求。
[En]
The first point is to decouple the business from the function, and the business layer focuses on the business, such as the network interface request. The business layer only needs to know which interface request method to call, but not how the interface request is initiated.
其次,创建一个小节,并在这个小节中添加一些一般性的附加操作,如注释解析、日志上报等,以避免在每个接口方法中编写这些一般性操作。
[En]
Second, create a section and add some general additional operations to this section, such as annotation parsing, log reporting, etc., to avoid writing these general operations in each interface method.