Insight into the underlying logic of design patterns

Ali Technology 2021-04-16 18:53:05
insight underlying logic design patterns


 picture


Design pattern is a topic that students often talk about , It is also often used in actual development projects , Skilled people can do it at will , People who are not familiar with you are in deep meditation . The author thinks , It's not just about mastering the usage of design patterns , More insight into the underlying logic of design patterns , That's all , Only in this way can practical problems be solved with appropriate design patterns .

One   You should focus on the underlying logic


1  Design patterns


Duan Ziyi : You ask him to tell you about design patterns , He tells you stories , After listening , Jump and jump , I'm so happy ; Look at the original design pattern and the actual code , Jump and jump again , That's crazy .

Duan zier : You ask him to tell you about design patterns , He told you about architecture ; You talk to him about architecture , He talks about architecture ; You talk to him about architecture , He talks to you about philosophy ……

The above two typical jokes , You can see the frustration of learning design patterns , I understand the story , But I still haven't mastered the design pattern , Even the class diagram of design pattern everyone I can draw , But still can't grasp the design pattern flexibly . The fundamental reason is that we have not mastered the core idea of design patterns , Just know the external form of design patterns , It's equivalent to only learning “ movements in martial arts or traditional opera ”, Didn't learn “ Internal skill ”.

2  The essence of underlying logic


Many things have underlying logic , After mastering the underlying logic of things , A lot of things are easy to do , If you've got an insight into the core laws , In practical work, we just need to follow the rules to carry out . for example , We've seen a lot of marketing copywriting 、 amazing , If we're going to write these marketing scripts , I couldn't find a way at first , The title is plain and light , Not attractive enough . What is the underlying logic behind marketing copywriting ? We see a lot of copywriting like “ Four strategies to stimulate learning potential ”、“ How to be in 10 Days to remember 5000+ word ”、“ Why are you worse than others ”…… Some of these copywriters use declarative techniques , Some use questioning techniques , Some use contrast , Some use exclamation …… And dig down , Either way , In essence, it's hitting people's comfort or pain points , Then use the underlying logic to see all kinds of copywriting , Some hit your pain spot , For example, you want to remember more words , Reality can't remember words ; For example, if you want to succeed , But after a long time of hard work, it has no effect …… Some hit your point : You can get better service for less money ; You can make money without going out …… When you get insight into the underlying logic behind marketing copywriting , You can also write eye-catching scripts now , That's the power of the underlying logic !

We learn 23 Design patterns , They are divided into creative design patterns 、 Structural design pattern 、 Behavioral design patterns , It's like the way marketing copywriting works , So what is the underlying logic of design patterns ?

 picture


Two   The underlying logic of design patterns


1  The cornerstone of design patterns


Usually when we write code , We often see the following three types of code : Noodle code 、 Procedural code and object-oriented code , Here is an example to illustrate the characteristics of these three types of coding .

  • Noodle code is all logic stacked together , It's like writing an article , Not very segmented . For example, ancient carved characters , Carve a poem on a piece of wood , If the poet wants to change one of them , Then we have to re carve the poem . It's very easy to see the drawbacks of this model : Coupling is too serious , Pull one hair and move the whole body .


  • Procedural code has made great progress on the basis of noodle code , It follows “ The top-down , Progressive refinement ” Thought , Divide a big problem into several small ones , Divide and rule . Corresponding to the example of carving poem above , A poem is made up of lines , If only one line of poetry was carved on each board , If you want to change a word , Just re sculpt that line , No need to re carve the whole poem . But if you have to change more than one word , And in different lines , In this extreme case, the whole poem has to be re carved .


  • Object oriented code is a new way of thinking , Poetry is made up of lines , Lines are made up of words , This is the idea of movable type printing , These words can also be used in different poems , It's very reusable .


As you can see from the above example , The core is insight into the structure and relationship of things , The first answer is what, instead of how. Procedural is overemphasized how, Start thinking about how to do it , Process thinking is self centered , Director of the entire functional process , I've taken on too many responsibilities I shouldn't have , The whole design is inflexible . Object oriented is to look at problems from the perspective of objects , Problem solving is done by the cooperation of various objects , The cornerstone of design patterns is object orientation , It's hooliganism to talk about design patterns without object orientation .

2  The originator of design patterns


There is a classic book on Design Patterns :《 Design patterns : Reusable The foundation of object-oriented software 》, In the book, the author mentioned a sentence :“ Find the change , Packaging changes , That's the underlying logic of design patterns . Many people ignore this sentence , Instead, we're going to pursue all kinds of moves , I can't find a suitable design pattern to solve the practical problems .“ Find the change , Packaging changes ” It's a very succinct reminder of the nature of design patterns , Savor this sentence , Let's see 23 Design patterns , Every design pattern is responding to change , For example, the strategic model , Specific strategies are changing ; Factory mode , The objects created are changing ; Template pattern , Specific template algorithm implementation is changing …… It's like the underlying logic of marketing copywriting : Hit your pain point or hit your cool point , What are the specific pain points and cool points . In practical terms , We need to see what's changing , Choose which design pattern is more appropriate .

3  Let's talk about the underlying logic


Looking back at the underlying logic , What we usually see is only the phenomenal layer , The core is to have an insight into the underlying logic of things , Only in that way can we really understand the phenomenon 、 Use the law , If you don't understand the underlying logic behind marketing copywriting , All your hard work is low level repetition , It's hard to write high quality marketing copy , Once or twice it works well, and you don't know why it's attractive . The same is true of design patterns , You can draw patterns with familiarity UML chart , But you still can't use design patterns well , In essence, I still don't master the underlying logic of design patterns , Only see the phenomenon of the design pattern, the moves of the layer . The underlying logic of design patterns is “ Find change turn , Packaging changes ”, Here are two questions : What is changing , How to encapsulate change , The master thought we all knew , So I didn't say how to look for change , How to encapsulate change . Next, let's talk about how to use the underlying logic of design patterns .

 picture

3、 ... and   Two questions to be answered by design patterns


1   What is changing


“ Find the change , Packaging changes ” this sentence , The first thing to answer is what's changing , If the change is not found , It's impossible to encapsulate change . The author here looks at the changes of objects from the perspective of object life cycle , Objects are created by , And then it's used , And finally, death . Objects change in three different dimensions : Changes in object structure 、 Changes in object specifications 、 Changes in object behavior . Take the change of object structure as an example , The relationship of objects is divided into two categories : Linear and nonlinear relations ( Trees and pictures ), In online relationships , How to solve the problem that the change of an object will not affect the associated object ? In the tree structure , How to solve the problem of increasing new objects ? In the graph structure , How to solve the problem of user-friendly use of complex systems ?

Finding change is the key , Different business issues , The problems of change are also different , The core is to find these changes . For example, changes in object specifications , There are quantitative changes 、 Change in type 、 Changes in appearance , This kind of thinking is necessary in the process of actual coding , Like creating an object , Let's go deeper , There are no other types of objects ? Has the quantity changed ?…… Only by finding these changes , How to encapsulate change is a technical problem , Next, we discuss how to encapsulate changes .

2  How to encapsulate change


In terms of the type of encapsulation , There's encapsulation of data 、 Method encapsulation 、 Type encapsulation, etc . In terms of specific packaging methods , The common ones are configuration items 、 Interface 、 Abstract method 、 class 、 annotation 、 Plug in and other specific means , Looking up, we mainly use inheritance 、 The combination method , Let's look at the principle of encapsulation , A common principle is a single responsibility 、 Opening and closing principle 、 Dependency inversion 、 The principle of segregation …… Most people focus more on how to encapsulate change , Not thinking deeply about what's changing .

 picture


Four   Using underlying logic to derive structural design patterns


1  Looking for changes in object structure


from UML see , There are dependencies between objects 、 generalization 、 Combine 、 polymerization , But in terms of structure, there are only two , Linear and nonlinear relations . The linear relationship is simple , It's a one-to-one relationship , There are two kinds of nonlinear relations : Tree relation and graph relation .

The structure of the relationship has changed , It means dependency has changed , Like changes in linear relationships ,A Rely on the B There is a change , here B Changes will affect A, How to do it B Changes in the environment do not affect A That's what we have to consider .

2  Coping with linear change


As mentioned above , If B There is a change , because A rely on B, Object A We need to change it too , How to reduce the impact on A What about the impact ? There are two ways : One is to solve the problem by increasing adaptation , The other is to solve it through agency . The point of both methods is that an object is not directly associated with a changing object , Whether it's adaptation or proxy , It's the introduction of a third party to communicate with B relation , A third party is responsible for B Interact ,B Yes A There is no perception . Some people immediately found a problem , Isn't that shifting the problem to a third party ? At first glance , That's true , If we think about it further , If you don't A To work with B Relationship , also E、F……, If B Once changed, all the related objects will change , The price is higher , If only with a third party , Just change one place , The cost is much less .

3  Dealing with nonlinear changes


Nonlinear relationships are more complex than linear relationships , There are two common ways : One is through the registration mechanism , The other is to shield complexity through the abstraction layer . When an object contains multiple objects , If you manage it directly , There are too many responsibilities to take on , It's better to solve it through the registration mechanism , Add an object , It is through the registration mechanism to actively inform the object . Another way is to mask complexity through the abstraction layer , Like the facade model , Avoid all the complexity in the facade , Provide a simple interface to the outside world .

 picture

5、 ... and   The way business changes


Design patterns still need to be applied to the actual business in order to play its value , Alan Shalloway Mention a point : There's no way to predict where it's going to change , But knowing where it might change . Usually when we do business requirement development , Have this awareness of change , Don't fall into process oriented thinking for a while , Don't just think about how to achieve it , It's about thinking about what it is , What will change , Like the number of objects 、 The appearance of the object 、 Type of object …… When you think about it clearly , In order to make the design more reasonable .

For example, when I did the settlement business before , After the investor's financial management is due , Will be the amount of principal and interest to investors , At the beginning, there was only Dahua payment channel , Here's a question to think about , Dahua payment is just a specific way to achieve , Is there any other way to pay , If there is, do abstract design , Design a general payment template class , Every time a new payment channel is connected , Just rewrite a few methods in the template class , Then Minsheng Bank paid 、 Serial payment .

 picture


6、 ... and   The way of object design


With the foreshadowing of the contents mentioned above , Here is a further summary of some thoughts on object design . There are three problems in object design : What are the objects ? What is the relationship between objects ? What are the responsibilities of the target ? When these three problems are sorted out clearly , Object design is much easier , It is also the core of object-oriented analysis and design . Normally speaking , We know that structure determines function , Function determines behavior , This is very consistent with people's logical understanding , But it's very difficult to understand the structure of objects , Just like the molecular structure of the new coronavirus is not so easy to crack , Especially complex business , The business objects it contains are not so easy to understand its structure .

We can think in reverse , When there is a business scenario , First think about what its responsibilities are , Think about which business objects should undertake the responsibility , This is also typical inductive thinking . For example, in the coupon business , Its business activities are just three : Construction of securities 、 Issuance of securities 、 Voucher , Any coupon system , It's going to provide these three most basic capabilities , These three capabilities correspond to two business objects : Coupon batch and coupon instance , The coupon batch is the template of the coupon , Tell me the budget of the coupon 、 How much is the coupon 、 What are the conditions of use ……, It's the voucher instance that is distributed to users .

When you have business objects , It is necessary to think about the attributes and methods contained in the object model through use cases , This process can not be completed perfectly at one time , It's a lot of polishing , There are some principles to follow , Like single responsibility 、 Opening and closing principle 、 Rely on the principle of inversion ……, Make the whole model more scalable .

 picture


7、 ... and   A case


Finally, take a case study , The store category is the classification made by the seller for the convenience of the buyer to choose the goods , For example, new categories , Put the recent 30 The commodities in the sky are grouped together , Easy for buyers to find . The challenge is how to use a business model to support the highly customized requirements of different business parties , Some demanders require three levels of categories , Some businesses require floating two-level categories , At the same time, there are different ways to circle products , Some businesses require automatic circle selection of products , The conditions for selecting products are not the same , If you circle by price 、 Circle and select according to the time when the goods are put on the shelves 、 Circle by evaluation ……

How to design this model , Or from the definition of shop category , The store category contains at least two key elements : Category structure and category circle , Because classification produces structure , Commodities produce circle products , Considering that the categories have different levels and circle conditions , So the first version of the model was quickly designed , From the model, we can see the demands that can support the business , In particular, in the circle conditions, the business party can customize various conditions and register them on the platform , See this design , The author's heart is still gratified .

But in the process of implementation , Some problems were found , Such as root class and subclass , There are two concepts in the business model , There should also be these two concepts in the code , It's the introduction of these two concepts , It's a lot of trouble to write code , There is no difference between them , Now they are artificially distinguished , A lot of logic has to be written twice . The author further optimized the model , It became the second version of the model , This model is simpler .

The two points I want to talk about here are to ensure the simplicity of the model and reduce the technical complexity , Technologists like to delve into technology , I like to apply some of the techniques I have learned to projects , It's actually a technical bias , Only in this way can we reflect the technical complexity and technical ability . Complexity is not necessarily technical , It's like the underlying laws of design patterns , The author doesn't have a long talk , It's just 8 A word " Find the change , Packaging changes ", That's the truth , We learn design patterns , Don't use it just to use design patterns , Be sure to think about why you use , What problems have been solved , It's worth it .

 picture




Free collection e-book

《 thorough MySQL actual combat 》


As the top two database in the world ,MySQL It has always been the first choice for developers to learn database . This book sums up MySQL Seven typical scenes in the actual combat of a large factory , And a detailed interpretation of Alibaba's self-developed open source database AliSQL In double 11 Application and practice in the scenario of equal concurrency .


Scan the code and make friends with ALI Mei , reply “mysql ” obtain Well ~( English letters are lowercase , If scan code is invalid , It can be done by WeChat ID alimei4、alimei5、alimei6、alimei7 Add... Directly )

 picture
版权声明
本文为[Ali Technology]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210416171727688i.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云