跳转到主要内容
Chinese, Simplified

在软件工程中,软件设计模式是对软件设计中给定上下文中常见问题的通用、可重用的解决方案。它不是一个可以直接转换为源代码或机器代码的完整设计。相反,它是一个描述或模板,用于说明如何解决一个可以在许多不同情况下使用的问题。设计模式是程序员在设计应用程序或系统时可以用来解决常见问题的形式化最佳实践。

面向对象的设计模式通常显示类或对象之间的关系和交互,而不指定涉及的最终应用程序类或对象。暗示可变状态的模式可能不适合于函数式编程语言,有些模式可能在内置支持解决其试图解决的问题的语言中变得不必要,而面向对象模式不一定适合于非面向对象语言。

设计模式可以被看作是介于编程范例和具体算法之间的计算机编程的结构化方法。

历史

图案最早起源于1966年克里斯托弗·亚历山大的一个建筑概念(c.f.“街道图案”,《美国建筑师协会期刊》,1966年9月,第32卷,第3期,第273-278页)。1987年,Kent Beck和Ward Cunningham开始尝试将模式应用到编程中,特别是模式语言,并在当年的OOPSLA会议上展示了他们的结果。[1][2]在接下来的几年里,Beck、Cunningham和其他人跟进了这项工作。

1994年,所谓的“四人帮”(Gamma等人)出版了《设计模式:可重用面向对象软件的元素》(Design patterns:Elements of Reusable Object Oriented Software)一书,此后设计模式在计算机科学中得到了广泛的应用。同年,第一届模式语言编程会议召开,第二年波特兰模式库成立,用于设计模式的文档。这一术语的范围仍有争议。设计模式类型的著名书籍包括:

伽玛,埃里希;赫尔姆,理查德;约翰逊,拉尔夫;弗利塞德斯,约翰(1995)。设计模式:可重用面向对象软件的元素。艾迪生·韦斯利。ISBN 978-0-201-63361-0。

Brinch Hansen,Per(1995年)。计算科学研究:并行程序设计范例。普伦蒂斯·霍尔。ISBN 978-0-13-439324-7。

弗兰克·布什曼;雷吉·梅尼尔;汉斯·罗赫内特;彼得·索默拉德(1996)。面向模式的软件体系结构,第1卷:模式系统。约翰威利父子公司。ISBN 978-0-471-95869-7。

贝克,肯特(1997)。Smalltalk最佳实践模式。普伦蒂斯·霍尔。ISBN 978-0134769042号。

施密特,道格拉斯C;斯大尔,迈克尔;罗赫内特,汉斯;巴斯曼,弗兰克(2000)。面向模式的软件体系结构,第2卷:并发和网络对象的模式。约翰威利父子公司。ISBN 978-0-471-60695-6。

福勒,马丁(2002)。企业应用程序体系结构的模式。艾迪生·韦斯利。ISBN 978-0-321-12742-6。

Hohpe,Gregor;Woolf,Bobby(2003年)。企业集成模式:设计、构建和部署消息传递解决方案。艾迪生·韦斯利。ISBN 978-0-321-20068-6。

弗里曼,埃里克T;罗布森,伊丽莎白;贝茨,伯特;塞拉,凯西(2004)。头部优先设计模式。奥雷利媒体。ISBN 978-0-596-00712-6。

尽管设计模式在实践中已经应用了很长一段时间,但设计模式概念的形式化却在过去的几年里一直停滞不前

练习

设计模式可以通过提供经过测试和验证的开发范例来加快开发过程。[4]有效的软件设计需要考虑到在实现的后期才可能出现的问题。新编写的代码通常会隐藏一些需要时间检测的微妙问题,这些问题有时会导致一些重大问题。重用设计模式有助于防止此类微妙的问题(需要引用),而且它还提高了熟悉模式的程序员和架构师的代码可读性。

为了实现灵活性,设计模式通常会引入额外的间接级别,这在某些情况下可能会使结果设计复杂化并损害应用程序性能。

根据定义,模式必须重新编程到每个使用它的应用程序中。由于一些作者认为这是从组件提供的软件重用中后退的一步,所以研究人员一直致力于将模式转换为组件。迈耶和阿诺特能够提供三分之二的模式的全部或部分组件化

软件设计技术很难应用于更广泛的问题。[需要引文]设计模式提供了一般的解决方案,以不需要特定问题的细节的格式记录。

结构

设计模式由几个部分组成(见下面的文档)。特别感兴趣的是结构、参与者和协作部分。这些章节描述了一个设计主题:一个典型的微型架构,开发人员复制并适应他们的特定设计,以解决设计模式描述的反复出现的问题。微体系结构是一组程序成分(如类、方法等)及其关系。开发人员通过在设计中引入这种典型的微架构来使用设计模式,这意味着他们设计中的微架构将具有与所选择的设计主题相似的结构和组织。

领域特定模式

还努力将特定领域的设计模式编码,包括使用现有的设计模式和特定领域的设计模式。示例包括用户界面设计模式、[6]信息可视化、[7]安全设计、[8]“安全可用性”、[9]Web设计[10]和业务模型设计。[11]

编程会议记录的年度模式语言[12]包括许多领域特定模式的例子。

分类和列表

根据设计模式所解决的问题类型,将其分为3个子类。创建模式提供了基于所需标准并以受控方式创建对象的能力。结构模式是组织不同的类和对象以形成更大的结构并提供新的功能。最后,行为模式是识别对象之间的通用通信模式并实现这些模式。

创建模式

Name Description In Design Patterns In Code Complete[13] Other
Abstract factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Yes Yes N/A
Builder Separate the construction of a complex object from its representation, allowing the same construction process to create various representations. Yes No N/A
Dependency Injection A class accepts the objects it requires from an injector instead of creating the objects directly. No No N/A
Factory method Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Yes Yes N/A
Lazy initialization Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. This pattern appears in the GoF catalog as "virtual proxy", an implementation strategy for the Proxy pattern. No No PoEAA[14]
Multiton Ensure a class has only named instances, and provide a global point of access to them. No No N/A
Object pool Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and thread pool patterns. No No N/A
Prototype Specify the kinds of objects to create using a prototypical instance, and create new objects from the 'skeleton' of an existing object, thus boosting performance and keeping memory footprints to a minimum. Yes No N/A
Resource acquisition is initialization (RAII) Ensure that resources are properly released by tying them to the lifespan of suitable objects. No No N/A
Singleton Ensure a class has only one instance, and provide a global point of access to it. Yes Yes N/A

结构模式

 

Name Description In Design Patterns In Code Complete[13] Other
Adapter, Wrapper, or Translator Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator. Yes Yes N/A
Bridge Decouple an abstraction from its implementation allowing the two to vary independently. Yes Yes N/A
Composite Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. Yes Yes N/A
Decorator Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality. Yes Yes N/A
Extension object Adding functionality to a hierarchy without changing the hierarchy. No No Agile Software Development, Principles, Patterns, and Practices[15]
Facade Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. Yes Yes N/A
Flyweight Use sharing to support large numbers of similar objects efficiently. Yes No N/A
Front controller The pattern relates to the design of Web applications. It provides a centralized entry point for handling requests. No No

J2EE Patterns[16] PoEAA[17]

Marker Empty interface to associate metadata with a class. No No Effective Java[18]
Module Group several related elements, such as classes, singletons, methods, globally used, into a single conceptual entity. No No N/A
Proxy Provide a surrogate or placeholder for another object to control access to it. Yes No N/A
Twin [19] Twin allows modeling of multiple inheritance in programming languages that do not support this feature. No No N/A

 

行为模式

Name Description In Design Patterns In Code Complete[13] Other
Blackboard Artificial intelligence pattern for combining disparate sources of data (see blackboard system) No No N/A
Chain of responsibility Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Yes No N/A
Command Encapsulate a request as an object, thereby allowing for the parameterization of clients with different requests, and the queuing or logging of requests. It also allows for the support of undoable operations. Yes No N/A
Interpreter Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Yes No N/A
Iterator Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Yes Yes N/A
Mediator Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to vary independently. Yes No N/A
Memento Without violating encapsulation, capture and externalize an object's internal state allowing the object to be restored to this state later. Yes No N/A
Null object Avoid null references by providing a default object. No No N/A
Observer or Publish/subscribe Define a one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically. Yes Yes N/A
Servant Define common functionality for a group of classes. The servant pattern is also frequently called helper class or utility class implementation for a given set of classes. The helper classes generally have no objects hence they have all static methods that act upon different kinds of class objects. No No N/A
Specification Recombinable business logic in a Boolean fashion. No No N/A
State Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Yes No N/A
Strategy Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Yes Yes N/A
Template method Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Yes Yes N/A
Visitor Represent an operation to be performed on the elements of an object structure. Visitor lets a new operation be defined without changing the classes of the elements on which it operates. Yes No N/A

并发模式

Name Description In POSA2[20] Other
Active Object Decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests. Yes N/A
Balking Only execute an action on an object when the object is in a particular state. No N/A
Binding properties Combining multiple observers to force properties in different objects to be synchronized or coordinated in some way.[21] No N/A
Compute kernel The same calculation many times in parallel, differing by integer parameters used with non-branching pointer math into shared arrays, such as GPU-optimized Matrix multiplication or Convolutional neural network. No N/A
Double-checked locking Reduce the overhead of acquiring a lock by first testing the locking criterion (the 'lock hint') in an unsafe manner; only if that succeeds does the actual locking logic proceed.

Can be unsafe when implemented in some language/hardware combinations. It can therefore sometimes be considered an anti-pattern.

Yes N/A
Event-based asynchronous Addresses problems with the asynchronous pattern that occur in multithreaded programs.[22] No N/A
Guarded suspension Manages operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed. No N/A
Join Join-pattern provides a way to write concurrent, parallel and distributed programs by message passing. Compared to the use of threads and locks, this is a high-level programming model. No N/A
Lock One thread puts a "lock" on a resource, preventing other threads from accessing or modifying it.[23] No PoEAA[14]
Messaging design pattern (MDP) Allows the interchange of information (i.e. messages) between components and applications. No N/A
Monitor object An object whose methods are subject to mutual exclusion, thus preventing multiple objects from erroneously trying to use it at the same time. Yes N/A
Reactor A reactor object provides an asynchronous interface to resources that must be handled synchronously. Yes N/A
Read-write lock Allows concurrent read access to an object, but requires exclusive access for write operations. No N/A
Scheduler Explicitly control when threads may execute single-threaded code. No N/A
Thread pool A number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. Can be considered a special case of the object pool pattern. No N/A
Thread-specific storage Static or "global" memory local to a thread. Yes N/A

文档

设计模式的文档描述了使用模式的上下文、模式试图解决的上下文中的力以及建议的解决方案。[24]没有单一的标准格式来记录设计模式。相反,不同的模式作者使用了多种不同的格式。然而,根据Martin Fowler的说法,某些模式形式已经变得比其他模式更为知名,因此成为新模式编写工作的共同出发点。[25]常用文档格式的一个例子是Erich Gamma、Richard Helm、Ralph Johnson和John Vlissides在其著作《设计模式》中使用的格式。它包含以下部分:

模式名称和分类:有助于识别和引用模式的描述性唯一名称。

意图:描述模式背后的目标和使用它的原因。

也被称为:模式的其他名称。

动机(力):一个场景,由一个问题和一个可以使用这个模式的上下文组成。

适用性:此模式可用的情况;模式的上下文。

结构:图案的图形表示。类图和交互图可用于此目的。

参与者:模式中使用的类和对象及其在设计中的角色的列表。

协作:描述模式中使用的类和对象如何相互作用。

结果:对使用该模式所导致的结果、副作用和权衡的描述。

实现:对模式实现的描述;模式的解决方案部分。

示例代码:演示如何在编程语言中使用模式。

已知用途:模式的实际用法示例。

相关模式:与模式有某种关系的其他模式;讨论模式与类似模式之间的差异。

批评

已经观察到,设计模式可能只是一个符号,在给定的编程语言(java或C++)中缺少某些特征。Peter Norvig演示了在设计模式书(主要是C++)中的23种模式中的16种在LISP或迪伦中被简化或消除(通过直接语言支持)。(26)由Hannemann和KiZales进行相关观察,使用面向方面编程实现了23种设计模式中的几种。language(AspectJ)指出,23个设计模式中的17个模式的实现中去掉了代码级的依赖关系,面向方面的编程可以简化设计模式的实现。[需要引文]另见Paul Graham的文章《书呆子的复仇》。[27]

不恰当地使用模式可能会不必要地增加复杂性

 

相关内容

 

原文:https://en.wikipedia.org/wiki/Software_design_pattern

本文:http://jiagoushi.pro/node/961

讨论:请加入知识星球或者微信圈子【首席架构师圈】

Tags
 
Article
知识星球
 
微信公众号
 
视频号