What’s a design pattern?
什么是设计模式?
Design patterns are typical solutions to commonly occurring problems in software design. They are like pre-made blueprints that you can customize to solve a recurring design problem in your code.
设计模式是软件设计中常见问题的典型解决方案。它们就像预制的蓝图,您可以自定义这些蓝图来解决代码中反复出现的设计问题。
You can’t just find a pattern and copy it into your program, the way you can with off-the-shelf functions or libraries. The pattern is not a specific piece of code, but a general concept for solving a particular problem. You can follow the pattern details and implement a solution that suits the realities of your own program.
你不能只是找到一个模式并将其复制到你的程序中,就像你使用现成的函数或库一样。模式不是一段特定的代码,而是解决特定问题的一般概念。您可以遵循模式详细信息,并实现适合您自己程序实际情况的解决方案。
Patterns are often confused with algorithms, because both concepts describe typical solutions to some known problems. While an algorithm always defines a clear set of actions that can achieve some goal, a pattern is a more high-level description of a solution. The code of the same pattern applied to two different programs may be different.
模式经常与算法混淆,因为这两个概念都描述了一些已知问题的典型解决方案。虽然算法始终定义一组可以实现某些目标的明确操作,但模式是对解决方案的更高级描述。应用于两个不同程序的相同模式的代码可能不同。
An analogy to an algorithm is a cooking recipe: both have clear steps to achieve a goal. On the other hand, a pattern is more like a blueprint: you can see what the result and its features are, but the exact order of implementation is up to you.
算法的类比是烹饪食谱:两者都有明确的步骤来实现目标。另一方面,模式更像是一个蓝图:你可以看到结果及其功能是什么,但实现的确切顺序取决于你。
What does the pattern consist of?
模式由什么组成?
Most patterns are described very formally so people can reproduce them in many contexts. Here are the sections that are usually present in a pattern description:
大多数模式都描述得非常正式,因此人们可以在许多情况下重现它们。以下是模式描述中通常存在的部分:
- Intent of the pattern briefly describes both the problem and the solution.
模式的意图简要描述了问题和解决方案。 - Motivation further explains the problem and the solution the pattern makes possible.
动机进一步解释了问题和模式使解决方案成为可能。 - Structure of classes shows each part of the pattern and how they are related.
类的结构显示了模式的每个部分以及它们之间的关系。 - Code example in one of the popular programming languages makes it easier to grasp the idea behind the pattern.
使用一种流行的编程语言的代码示例可以更容易地掌握模式背后的思想。
Some pattern catalogs list other useful details, such as applicability of the pattern, implementation steps and relations with other patterns.
一些模式目录列出了其他有用的细节,例如模式的适用性、实现步骤以及与其他模式的关系。