设计模式之装饰器模式

Java61

本文由老王将建好的书房计划请小王来帮忙,小王却想谋权篡位,老王通过教育他引出装饰器设计模式,第二部分针对老王提出的建设性意见实现装饰器模式,第三部分针对装饰器模式在Jdk中的IO、Spring中的缓存管理器、Mybatis的运用来加强我们的理解,第四部分说明装饰器模式和代理模式的区别及他们各自的应用场景。

读者可以拉取完整代码到本地进行学习,实现代码均测试通过后上传到码云

一、引出问题

上篇文章对老王的书架改造以后,老王是相当的满意,看小王能力突出,这不老王又有了新的需求。

合并模式后,老王的图书管理得很好,但随着图书的增加,老王忙得不可开交。老王想让小王帮他做一些额外的事情,比如在买书之前打扫书房。晚上锁上书房的门;或者在别人借书之前做笔记,借书人还书后小王收到,等等。

[En]

After the combination mode, Lao Wang's books are well managed, but with the increase of books, Lao Wang is too busy. Lao Wang wants Xiao Wang to help him with some extra things, such as cleaning the study before buying the book. lock the door of the study in the evening; or take notes before someone borrows the book, and Xiao Wang receives it after the borrower returns the book, and so on.

小王听后说,这有多难。之后,他挽起袖子,准备给老王改密码。老王连忙拦住他。你真是个傻瓜。你为什么要移动我写的代码?如果您更改它,是否会影响我的业务逻辑?我通常会让你读更多的书,而你却不听。你以前学过的设计模式怎么样?别把它拿出来让他吃灰烬。

[En]

After hearing this, Xiao Wang said how difficult it was. After that, he rolled up his sleeves and was ready to change Lao Wang's code. Lao Wang hurriedly stopped him. You are such a fool. Why should you move the code I wrote? will it affect my business logic if you change it? I usually let you read more and you don't listen. What about the design patterns you learned before? Don't take it out and let him eat ash.

小王不好意思的挠挠头,翻出来了他的设计模式宝典,开始寻找合适的设计模式。

小王大喊有了,之前说过的代理模式可以很好的解决这个问题,代理模式可以动态的增强对象的一些特性,我准备使用代理模式完成这个需求。

老王听后不由得摇了摇头。看来你要篡夺王位了。你想要我整个学习的权利。

[En]

After hearing this, Lao Wang could not stop shaking his head. It seems that you are going to usurp the throne. You want the right of my whole study.

老王解释说,代理模式可以达到这一要求,但在这种场景下,显然代理模式并不合适。主体模型侧重于对对象的控制。我们今天的诉求是在对象的基础上增加他的一些功能,我们各自的业务发展是互不干扰的。

[En]

Lao Wang explained that the agent model can achieve this requirement, but in this scenario, it is obvious that the agent model is not appropriate. The agent model focuses on the control of the object. Our demand today is to add some of his functions on the basis of the object, and our respective business development does not interfere with each other.

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长