.NET 7 Design Patterns In-Depth
Enhance code efficiency and maintainability with .NET Design Patterns
Vahid Farahmandian
Table of Contents
目录
-
Introduction to Design Patterns
-
设计模式简介
-
Creational Design Patterns
-
创造式设计模式
-
Structural Design Patterns
-
结构设计模式
-
Behavioral Design Patterns – Part I
-
行为设计模式 – 第一部分
-
Behavioral Design Patterns – Part II
-
行为设计模式 – 第二部分
-
Domain Logic Design Patterns
-
域逻辑设计模式
-
Data Source Architecture Design Patterns
-
数据源架构设计模式
-
Object-Relational Behaviors Design Patterns
-
对象关系行为设计模式
-
Object-Relational Structures Design Patterns
-
对象关系结构设计模式
-
Object-Relational Metadata Mapping Design Patterns
-
对象关系元数据映射设计模式
-
Web Presentation Design Patterns
-
Web 表示设计模式
12 . Distribution Design Patterns
12 .分布设计模式
-
Offline Concurrency Design Patterns
-
离线并发设计模式
-
Session State Design Patterns
-
会话状态设计模式
-
Base Design Patterns
-
基本设计模式
About the Author
关于作者
Vahid Farahmandian, who currently works as the CEO of Spoota company, was born in Urmia, Iran, in 1989. He got a BSc in Computer Software Engineering from Urmia University and an MSc degree in Medical Informatics from Tarbiat Modares University. He has more than 17 years of experience in the information and communication technology field and more than a decade of experience in teaching different courses of DevOps, programming languages, and databases in various universities, institutions, and organizations in Iran. Vahid also is an active speaker in international shows and conferences, including Microsoft .NET Live TV, Azure, .NET, and SQL Server conferences. The content published by Vahid was available through YouTube and Medium and had thousands of viewers and audiences.
Vahid Farahmandian 目前担任 Spoota 公司的首席执行官,于 1989 年出生于伊朗乌尔米亚。他获得了乌尔米亚大学的计算机软件工程学士学位和塔尔比亚特莫达雷斯大学的医学信息学硕士学位。他在信息和通信技术领域拥有超过 17 年的经验,并在伊朗的各所大学、机构和组织中教授 DevOps、编程语言和数据库的不同课程方面拥有十多年的经验。Vahid 还是国际节目和会议的积极演讲者,包括 Microsoft .NET Live TV、Azure、.NET 和 SQL Server 会议。Vahid 发布的内容可通过 YouTube 和 Medium 获得,并拥有成千上万的观众和观众。
About the Reviewers
关于审阅者
Kratika Jain is a senior software developer specializing in .NET technologies. She has a strong understanding of C#, ASP.NET, MVC, .NET Core, SQL, and Entity Framework. She has participated in agile project management, employs continuous integration/deployment (CI/CD) using Azure DevOps, and delivered robust and scalable software solutions. As a meticulous technical reviewer, she ensures accuracy and quality in technical content. Her attention to detail allows her to identify potential pitfalls and offer valuable insights for improvement. With her expertise in .NET development and dedication to enhancing technical content, she contributes to empowering developers and enabling their success in mastering the .NET ecosystem. She is a natural problem solver, team player, adaptable, and always seeking new challenges. You can connect with her on LinkedIn at www.linkedin.com/in/kratikajain29/ or on Twitter via @_KratikaJain.
Kratika Jain 是一位专门从事 .NET 技术的高级软件开发人员。她对 C#、ASP.NET、MVC、.NET Core、SQL 和实体框架有很强的理解。她参与了敏捷项目管理,使用 Azure DevOps 采用持续集成/部署 (CI/CD),并提供了强大且可扩展的软件解决方案。作为一名一丝不苟的技术审查员,她确保技术内容的准确性和质量。她对细节的关注使她能够识别潜在的陷阱并提供有价值的改进见解。凭借她在 .NET 开发方面的专业知识和对增强技术内容的奉献精神,她为增强开发人员的能力并帮助他们成功掌握 .NET 生态系统做出了贡献。她是一个天生的问题解决者、团队合作者、适应性强,并且总是寻求新的挑战。您可以通过 LinkedIn at www.linkedin.com/in/kratikajain29/ 或通过 @_KratikaJain 在 Twitter 上与她联系。
Gourav Garg is a Senior Software Engineer from India who has been helping companies to build scalable products. He holds a bachelor’s degree in software engineering and has been programming for 11 years. He is proficient in .net, C#, and Entity Framework. He has experience in delivering several products and many features at his work.
Gourav Garg 是来自印度的高级软件工程师,一直在帮助公司构建可扩展的产品。他拥有软件工程学士学位,从事编程工作已有 11 年。他精通 .net、C# 和 Entity Framework。他在工作中拥有交付多种产品和许多功能的经验。
Gourav has also experience with JavaScript-related tech stacks like Angular and React. He has developed quite a few open-source libraries using ES6 and Angular.
Gourav 还拥有 Angular 和 React 等 JavaScript 相关技术堆栈的经验。他使用 ES6 和 Angular 开发了不少开源库。
Acknowledgement
致谢
There are a few people I want to thank for the continued and ongoing support they have given me during the writing of this book. First and foremost, I would like to thank my parents for continuously encouraging me to write the book — I could have never completed this book without their support.
我想感谢一些人,他们在写这本书期间给予我持续的支持。首先,我要感谢我的父母一直鼓励我写这本书——如果没有他们的支持,我永远不可能完成这本书。
I also need to thank my dear wife, who has always supported me. Finally, I would like to thank all my friends and colleagues who have been by my side and supported me during all these years. I really could not stand where I am today without the support of all of them.
我还需要感谢我一直支持我的亲爱的妻子。最后,我要感谢这些年来一直陪伴在我身边并支持我的所有朋友和同事。如果没有他们所有人的支持,我真的无法站今天。
My gratitude also goes to the team at BPB Publications, who supported me and allowed me to write and finish this book.
我还要感谢 BPB Publications 的团队,他们支持我并允许我编写和完成这本书。
Preface
前言
This book has tried to present important design patterns (including GoF design patterns and Patterns of Enterprise Application Architecture) in software production with a simple approach, along with practical examples using .NET 7.0 and C#.
本书试图用简单的方法呈现软件生产中重要的设计模式(包括 GoF 设计模式和企业应用程序架构模式),以及使用 .NET 7.0 和 C# 的实际示例。
This book will be useful for software engineers, programmers, and system architects. Readers of this book are expected to have intermediate knowledge of C#.NET programming language, .NET 7.0, and UML.
这本书对软件工程师、程序员和系统架构师很有用。本书的读者应具备 C#.NET 编程语言、.NET 7.0 和 UML 的中级知识。
Practical and concrete examples have been used in writing this book. Each design pattern begins with a short descriptive sentence and is then explained as a concrete scenario. Finally, each design pattern's key points, advantages, disadvantages, applicability, and related patterns are stated.
在撰写本书时,使用了实际和具体的例子。每个设计模式都以一个简短的描述性句子开头,然后作为具体场景进行解释。最后,陈述了每种设计模式的关键点、优点、缺点、适用性和相关模式。
This book is divided into 15 chapters, including:
本书分为 15 章,包括:
Chapter 1: Introduction to Design Patterns- In this chapter, an attempt has been made to explain why design patterns are important and their role in software architecture, and basically, what is the relationship between design patterns, software design problems, and software architecture? In this chapter, various topics such as Design Principles, including SOLID, KISS, DRY, etc., and Introduction to .NET and UML are covered too.
第 1 章:设计模式简介 - 在本章中,我们试图解释为什么设计模式很重要以及它们在软件架构中的作用,基本上,设计模式、软件设计问题和软件架构之间的关系是什么?在本章中,还涵盖了各种主题,例如设计原则,包括 SOLID、KISS、DRY 等,以及 .NET 和 UML 简介。
Chapter 2: Creational Design Patterns- Creative design patterns, as the name suggests, deal with the construction of objects and how to create instances. In C# programming language, wherever an object is needed, the object can be created using the “new” keyword along with the class name. However, there are situations where it is necessary to hide the way the object is made from the user's view. In this case, creative design patterns can be useful. In this chapter, creational design patterns, one of the types of GoF design patterns, have been introduced, and it has been said that these design patterns are useful for what issues.
第 2 章:创造性设计模式 - 顾名思义,创意设计模式涉及对象的构造以及如何创建实例。在 C# 编程语言中,只要需要对象,就可以使用 “new” 关键字和类名创建对象。但是,在某些情况下,有必要从用户的视图中隐藏对象的创建方式。在这种情况下,创意设计模式可能很有用。在本章中,介绍了 GoF 设计模式的一种创建设计模式,并且据说这些设计模式对哪些问题很有用。
Chapter 3: Structural Design Patterns- Structural design patterns deal with the relationships between classes in the system. In fact, this category of design patterns determines how different objects can form a more complex structure together. In this chapter, structural design patterns, one of the types of GoF design patterns, have been introduced, and it has been said that these design patterns are useful for what issues.
第 3 章:结构设计模式 - 结构设计模式处理系统中类之间的关系。事实上,这类设计模式决定了不同的对象如何一起形成更复杂的结构。在本章中,介绍了 GoF 设计模式的一种结构设计模式,据说这些设计模式对什么问题很有用。
Chapter 4: Behavioral Design Patterns - Part I- This category of design patterns deals with the behavior of objects and classes. In fact, the main goal and focal point of this category of design patterns is to perform work between different objects using different methods and different algorithms. In fact, in this category of design patterns, not only objects and classes are discussed, but the relationship between them is also discussed. In this chapter, the most popular and famous behavioral design patterns, one of the types of GoF design patterns, have been introduced, and it has been said that these design patterns are useful for what issues.
第 4 章:行为设计模式 – 第一部分 - 这类设计模式涉及对象和类的行为。事实上,这类设计模式的主要目标和焦点是使用不同方法和不同算法在不同对象之间执行工作。事实上,在这类设计模式中,不仅讨论了对象和类,还讨论了它们之间的关系。在本章中,介绍了最流行和最著名的行为设计模式,这是 GoF 设计模式的一种,据说这些设计模式对什么问题很有用。
Chapter 5: Behavioral Design Patterns - Part II- In continuation of the previous chapter, in this chapter, more complex and less used behavioral design patterns are discussed, and it is shown how these design patterns can be useful in dealing with the behavior of objects and classes. Although these patterns are less known or less used, their use can make much more complex problems be solved in a very simple way. In this chapter, less popular or famous behavioral design patterns, one of the types of GoF design patterns, have been introduced, and it has been said that these design patterns are useful for what issues.
第 5 章:行为设计模式 – 第二部分 - 在上一章的延续中,本章讨论了更复杂和较少使用的行为设计模式,并展示了这些设计模式如何用于处理对象和类的行为。尽管这些模式鲜为人知或较少使用,但它们的使用可以以非常简单的方式解决更复杂的问题。在本章中,介绍了不太流行或不太著名的行为设计模式,这是 GoF 设计模式的一种类型,据说这些设计模式对什么问题很有用。
Chapter 6: Domain Logic Design Patterns- To organize domain logic, Domain Logic design patterns can be used. The choice of which design pattern to use depends on the level of logical complexity that we want to implement. The important thing here is to understand when logic is complex and when it is not! Understanding this point is not an easy task, but by using domain experts, or more experienced people, it is possible to obtain a better approximation. In this chapter, it is said how to organize the logic of the domain. And in this way, what are the design patterns that help us have a more appropriate and better design? These design patterns are among the PoEAA design patterns.
第 6 章:域逻辑设计模式 - 为了组织域逻辑,可以使用域逻辑设计模式。选择使用哪种设计模式取决于我们想要实现的逻辑复杂程度。这里重要的是了解逻辑何时复杂,何时不复杂!理解这一点并非易事,但通过使用领域专家或更有经验的人,可以获得更好的近似值。在本章中,将介绍如何组织域的逻辑。而这样一来,有哪些设计模式可以帮助我们有一个更合适、更好的设计呢?这些设计模式属于 PoEAA 设计模式。
Chapter 7: Data Source Architectural Design Patterns- One of the challenges of designing the data access layer is to implement how to communicate with the data source. In this implementation, it is necessary to address issues such as how to categorize SQL codes, how to manage the complexities of communicating with the data of each domain, and the mismatch between the database structure and the domain model. In this chapter, it has been said that in software architecture, communication with data sources can be considered and implemented in a suitable way. These design patterns are among the PoEAA design patterns.
第 7 章:数据源架构设计模式 - 设计数据访问层的挑战之一是实现如何与数据源通信。在此实现中,有必要解决诸如如何对 SQL 代码进行分类、如何管理与每个域的数据进行通信的复杂性以及数据库结构和域模型之间的不匹配等问题。在本章中,已经说过在软件架构中,可以考虑并以适当的方式实现与数据源的通信。这些设计模式属于 PoEAA 设计模式。
Chapter 8: Object-Relational Behaviors Design Patterns- Among the other challenges that exist when communicating with the database is paying attention to behaviors. What is meant by behaviors is how the data should be fetched from the database or how it should be stored in it. For example, suppose a lot of data is fetched from the database, and some of them have changed. It will be very important to answer the question of which of the data has changed or how to store the changes again in the database, provided that the data consistency is not disturbed. Another challenge is that when the Domain Model is used, most of the models have relationships with other models, and reading a model will lead to fetching all its relationships, which will again jeopardize the efficiency. In this chapter, an attempt has been made to explain how to connect business to data sources in a proper way. These design patterns are among the PoEAA design patterns.
第 8 章:对象关系行为设计模式 - 与数据库通信时存在的其他挑战之一是关注行为。行为的含义是应该如何从数据库中获取数据或应该如何将数据存储在数据库中。例如,假设从数据库中获取了大量数据,其中一些数据已更改。回答哪些数据已更改或如何将更改再次存储在数据库中的问题非常重要,前提是数据一致性不受干扰。另一个挑战是,当使用 Domain Model 时,大多数模型都与其他模型有关系,读取一个模型会导致获取它的所有关系,这将再次危及效率。在本章中,我们尝试解释如何以适当的方式将业务连接到数据源。这些设计模式属于 PoEAA 设计模式。
Chapter 9: Object-Relational Structures Design Patterns- Another challenge in mapping the domain to the database is how to map a record in the database to an object. The next challenge is how to implement all types of relationships, including one-to-one, one-to-many and many-to-many relationships. In the meantime, we may face some data that cannot and should not be mapped to any table, and we should think about this problem in our design. Finally, to implement the structure of the database, relationships such as inheritance may be used. In this case, it should be determined how this type of implementation should be mapped to the tables in the database. In this chapter, an attempt has been made to explain how to implement the data source structure in the software. These design patterns are among the PoEAA design patterns.
第 9 章:对象关系结构设计模式 - 将域映射到数据库的另一个挑战是如何将数据库中的记录映射到对象。下一个挑战是如何实现所有类型的关系,包括 1 对 1、1 对多和 many-to-many 关系。同时,我们可能会遇到一些不能也不应该映射到任何 table 的数据,我们应该在设计中考虑这个问题。最后,为了实现数据库的结构,可以使用继承等关系。在这种情况下,应确定如何将这种类型的实现映射到数据库中的表。在本章中,尝试解释如何在软件中实现数据源结构。这些设计模式属于 PoEAA 设计模式。
Chapter 10: Object-Relational Metadata Mapping Design Patterns- When we are producing software, we need to implement the mapping between tables and classes. For the software production process, this will be a process that contains a significant amount of repetitive code, and this will increase the production time. So, it will be necessary to stop writing duplicate codes and extract relationships from metadata. When this challenge can be solved, then it will be possible to generate queries automatically. Finally, when it is possible to automatically extract queries, the database can be hidden from the rest of the program. This chapter describes how to store object metadata in the data source, as well as how to create and manage queries to the data source. These design patterns are among the PoEAA design patterns.
第 10 章:对象关系元数据映射设计模式 - 当我们生产软件时,我们需要实现表和类之间的映射。对于软件生产过程,这将是一个包含大量重复代码的过程,这将增加生产时间。因此,有必要停止编写重复代码并从元数据中提取关系。当这个挑战可以解决时,就可以自动生成查询。最后,当可以自动提取查询时,数据库可以对程序的其余部分隐藏。本章介绍如何在数据源中存储对象元数据,以及如何创建和管理对数据源的查询。这些设计模式属于 PoEAA 设计模式。
Chapter 11: Web Presentation Design Patterns- One of the most important changes in applications in recent years is the penetration of web-based user interfaces. These types of interfaces come with various advantages, including that the client often does not need to install a special program to use them. The creation of web applications is often accompanied by the generation of server-side codes. The request is entered into the web server, and then the web server delivers the request based on the content of the request to the web application or the corresponding website. To separate the details related to the view from the data structure and logic, you can benefit from the design patterns presented in this chapter. In this chapter, the creation and handling of user interface requests are discussed, and it is stated how you can prepare and implement the view and how you can manage the requests in a suitable way. These design patterns are among the PoEAA design patterns.
第 11 章:Web 表示设计模式 - 近年来应用程序最重要的变化之一是基于 Web 的用户界面的渗透。这些类型的接口具有各种优点,包括客户端通常不需要安装特殊程序即可使用它们。Web 应用程序的创建通常伴随着服务器端代码的生成。将请求输入到 Web 服务器中,然后 Web 服务器根据请求的内容将请求投递到 Web 应用程序或相应的网站。要将与视图相关的细节与数据结构和逻辑分开,您可以从本章中介绍的设计模式中受益。在本章中,讨论了用户界面请求的创建和处理,并说明了如何准备和实现视图以及如何以适当的方式管理请求。这些设计模式属于 PoEAA 设计模式。
Chapter 12: Distribution Design Patterns- One of the problems of implementing communication between systems is observing the level of coarseness and fineness of communication. This level should be such that both the effectiveness and efficiency during the network are not disturbed, and the data structure delivered to the client is the structure that is expected and suitable for the client. In this chapter, design patterns that can be useful in building distributed software are discussed. These design patterns are among the PoEAA design patterns.
第 12 章:分布设计模式 - 在系统之间实现通信的问题之一是观察通信的粗略程度和精细度。这个级别应该是这样的,网络期间的有效性和效率都不会受到干扰,并且交付给客户端的数据结构是客户预期和适合的结构。本章讨论了在构建分布式软件时有用的设计模式。这些设计模式属于 PoEAA 设计模式。
Chapter 13: Offline Concurrency Design Patterns- One of the most complicated parts of software production is dealing with topics related to concurrency. Whenever several threads or processes have access to the same data, there is a possibility of problems related to concurrency, so one should think about concurrency in software production. Of course, there are different solutions at different levels for working and managing concurrency in enterprise software applications. For example, you can use transactions, internal features of relational databases, etc., for this purpose. Of course, this reason is not proof of the claim that concurrency management can basically be blamed on these methods and tools. In this chapter, design patterns that can be useful in solving these problems have been introduced. These design patterns are among the PoEAA design patterns.
第 13 章:离线并发设计模式 - 软件生产中最复杂的部分之一是处理与并发相关的主题。每当多个线程或进程可以访问相同的数据时,就可能存在与并发相关的问题,因此应该考虑软件生产中的并发性。当然,在企业软件应用程序中工作和管理并发在不同级别有不同的解决方案。例如,为此,您可以使用事务、关系数据库的内部功能等。当然,这个原因并不能证明并发管理基本上可以归咎于这些方法和工具的说法。本章介绍了可用于解决这些问题的设计模式。这些设计模式属于 PoEAA 设计模式。
Chapter 14: Session State Design Patterns- When we talk about transactions, we often talk about system transactions and business transactions. This discussion continues to the discussion of stateless or stateless sessions. Obviously, first, it should be determined what is meant by Stateful or Stateless. When we look at an object, this object consists of a series of data (status) and a series of behaviors. If we assume that the object does not contain any data, then we have accepted that the object in question does not have any data with it. If we bring this discussion to enterprise software, the meaning of Stateless will be a state in which the server does not keep any data of the request between two requests. If the server needs to store data between two requests, then we will face stateful mode. This chapter talks about how to manage user sessions. Some points have been raised regarding stateless and stateful sessions. These design patterns are among the PoEAA design patterns.
第 14 章:会话状态设计模式 - 当我们谈论事务时,我们经常谈论系统事务和业务事务。此讨论将继续讨论 stateless 或 stateless 会话。显然,首先,应该确定 Stateful 或 Stateless 的含义。当我们查看一个对象时,这个对象由一系列数据 (status) 和一系列 Behavior 组成。如果我们假设该对象不包含任何数据,则我们已接受该对象不包含任何数据。如果我们把这个讨论带到企业软件上,Stateless 的含义将是服务器在两个请求之间不保留请求的任何数据的状态。如果服务器需要在两个请求之间存储数据,那么我们将面临 Stateful 模式。本章讨论如何管理用户会话。已经提出了一些关于无状态和有状态会话的观点。这些设计模式属于 PoEAA 设计模式。
Chapter 15: Base Design Patterns- When we are designing software, we need to use different design patterns. To use these patterns, it is also necessary to use a series of basic design patterns to finally provide a suitable and better design. In fact, basic design patterns provide the foundation for designing and using other patterns. In this chapter, a series of basic design patterns have been introduced, and it has been shown how the use of these design patterns can be effective on the use of other design patterns. These design patterns are among the PoEAA design patterns.
第 15 章:基本设计模式 - 当我们设计软件时,我们需要使用不同的设计模式。要使用这些模式,还需要使用一系列基本的设计模式,以最终提供合适且更好的设计。事实上,基本设计模式为设计和使用其他模式提供了基础。在本章中,介绍了一系列基本设计模式,并展示了如何使用这些设计模式来有效地使用其他设计模式。这些设计模式属于 PoEAA 设计模式。
Code Bundle and Coloured Images
代码包和彩色图像
Please follow the link to download the Code Bundle and the Coloured Images of the book:https://rebrand.ly/g3mn07e
请点击链接下载代码包和书籍的彩色图像: https://rebrand.ly/g3mn07e
The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/.NET-7-Design-Patterns-In-Depth. In case there's an update to the code, it will be updated on the existing GitHub repository.
该书的代码包也托管在 GitHub 上,网址为 https://github.com/bpbpublications/.NET-7-Design-Patterns-In-Depth。如果代码有更新,它将在现有的 GitHub 存储库上更新。
We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out!
我们在 https://github.com/bpbpublications 上提供了丰富的书籍和视频目录中的代码包。看看他们吧!
Errata
勘误表
We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at :errata@bpbonline.com
我们为我们在 BPB Publications 的工作感到非常自豪,并遵循最佳实践来确保我们内容的准确性,从而为我们的订阅者提供沉迷的阅读体验。我们的读者是我们的镜子,我们利用他们的意见来反映和改进在所涉及的发布过程中可能发生的人为错误(如果有)。为了让我们保持质量并帮助我们联系任何可能因任何不可预见的错误而遇到困难的读者,请写信给我们:errata@bpbonline.com
Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family.
BPB Publications 大家庭高度感谢您的支持、建议和反馈。