Design Patterns (book): Difference between revisions

From Citizendium
Jump to navigation Jump to search
imported>Pat Palmer
(bringing over Design Patterns because I wrote a large portion of it)
 
imported>Pat Palmer
(→‎Observer: defining when it is used)
 
(46 intermediate revisions by 5 users not shown)
Line 1: Line 1:
[[Image:Book_designpatterns.gif|thumb]]
{{subpages}}
:''This article is about the book by Gamma et al. For other meanings, see [[design pattern]]''.


Often referred to as the '''''GoF''''', or '''''Gang-Of-Four''''' (because of the four authors who wrote it), '''''Design Patterns: Elements of Reusable Object-Oriented Software'''''(ISBN 0-201-63361-2) is a [[software engineering]] book describing recurring solutions to common problems in software design. The book's authors are [[Erich Gamma]], [[Richard Helm]], [[Ralph Johnson]], and [[John Vlissides]]. The book is divided into two parts, with the first two chapters exploring the capabilities and pitfalls of object-oriented programming, and the remaining chapters describing a series of classic [[Design pattern (computer science)|software design pattern]]s. The book includes examples in [[C++]] and [[Smalltalk]].  
'''Design Patterns: Elements of Reusable Object-Oriented Software''' (ISBN 0-201-63361-2) is a landmark book, first published in 1995, that recommends a set of best practices for object-oriented design and catalogs a variety of object-oriented software architectures illustrated in [[C++]] and [[Smalltalk]]<ref name="DesignPattern1">{{cite web|url=http://www.awprofessional.com/title/0201633612|title=Design Patterns: Elements of Reusable Object-Oriented Software|publisher=Addison-Wesley|year=2007|accessdate=2007-05-24}}</ref>.  In its 36th printing as of April 2007, the book has been translated into more than a dozen languages and has been highly regarded in the field of [[software engineering]]. However, the book makes for such dense reading (even for experienced programmers) that it has been superseded, in practice, by a spate of more recent, accessibly-written books despite being regarded as an important source for object-oriented design theory.  


The original publication date of the book was October 21, 1994 with a 2005 copyright, and as of April 2007, the book was in its 36th printing. The book was first made available to the public at the OOPSLA meeting held in Portland, Oregon in October 1994.  Powell's was the official show bookstore.  It has been highly influential to the field of software engineering and is  regarded as an important source for object-oriented design theory and practice. More than 500,000 copies have been sold in English and in 13 other languages.
The book's authors ([[Erich Gamma]], [[Richard Helm]], [[Ralph Johnson]], and [[John Vlissides]]) are commonly spoken of as ''the gang of four'' due to difficulties in speaking or remembering all their names at once.  


==Introduction, Chapter 1==
== Chapter 1 summary: Overview and Philosophy ==
Chapter 1 is a discussion of [[object-oriented]] design techniques, based on the authors' experience, which they believe would lead to good object-oriented software design, including:
Chapter 1 is a discussion of [[object-oriented]] design techniques, based on the authors' experience, which they believe would lead to good object-oriented software design.


* "Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)
=== When to use Interfaces vs. Inheritance ===
* "Favor '[[object composition]]' over '[[Inheritance_%28computer_science%29|class inheritance]]'." (Gang of Four 1995:20)
 
* "Program to an 'interface', not an 'implementation'." (page 18)<ref name="DesignPattern1" />
* "Favor '[[object composition]]' over '[[Inheritance_%28computer_science%29|class inheritance]]'." (page 20)<ref name="DesignPattern1" />


The authors claim the following as advantages of [[Interface_%28computer_science%29|interfaces]] over [[Inheritance_%28computer_science%29|inheritance]]:
The authors claim the following as advantages of [[Interface_%28computer_science%29|interfaces]] over [[Inheritance_%28computer_science%29|inheritance]]:
Line 16: Line 17:
* clients remain unaware of the specific types of objects they use, as long as the object adheres to the interface
* clients remain unaware of the specific types of objects they use, as long as the object adheres to the interface
* clients remain unaware of the classes that implement these objects; clients only know about the abstract class(es) defining the interface
* clients remain unaware of the classes that implement these objects; clients only know about the abstract class(es) defining the interface
=== Inheritance as White-box Software Engineering, Object Composition as Black-box SE ===


The authors refer to [[inheritance]] as ''[[White_box_%28software_engineering%29|white-box reuse]]'', with
The authors refer to [[inheritance]] as ''[[White_box_%28software_engineering%29|white-box reuse]]'', with
Line 25: Line 28:
composed objects need be visible in the code using them.
composed objects need be visible in the code using them.


The authors discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance (Gang of Four 1995:20).  The danger is stated as follows:
=== Inheritance overused; when and how to use it; pitfalls ===
 
The authors discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance (page 20)<ref name="DesignPattern1" />.  The danger is stated as follows:


"Because inheritance exposes a [[Subclass_%28computer_science%29|subclass]] to details of its parent's implementation,
"Because inheritance exposes a [[Subclass_%28computer_science%29|subclass]] to details of its parent's implementation,
it's often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)
it's often said that 'inheritance breaks encapsulation'". (page 19)<ref name="DesignPattern1" />


They warn that the implementation of
They warn that the implementation of
Line 39: Line 44:
of existing components, reusing most of the old code and adding relatively
of existing components, reusing most of the old code and adding relatively
small amounts of new code.
small amounts of new code.
=== Delegates as run-time linking ===


To the authors, 'delegation' is an extreme form of object composition
To the authors, 'delegation' is an extreme form of object composition
Line 45: Line 52:
to let the delegate refer to the receiver.  Thus the link between two parts
to let the delegate refer to the receiver.  Thus the link between two parts
of a system are established only at runtime, not at compile-time.  The [[Callback_%28computer_science%29|Callback]] article has more information about delegation.
of a system are established only at runtime, not at compile-time.  The [[Callback_%28computer_science%29|Callback]] article has more information about delegation.
=== Generics (Templates in C++) ===


The authors also discuss so-called '''parameterized types''', which are also known as generics (Ada, Eiffel, Java, C#) or templates (C++).  These allow a type to be defined without specifying all the other types it uses--the unspecified types are supplied as 'parameters' at the point of use.
The authors also discuss so-called '''parameterized types''', which are also known as generics (Ada, Eiffel, Java, C#) or templates (C++).  These allow a type to be defined without specifying all the other types it uses--the unspecified types are supplied as 'parameters' at the point of use.
=== Warning about Delegates and Generics ===


The authors admit that delegation and parameterization are  
The authors admit that delegation and parameterization are  
very powerful but add a warning:
very powerful but add a warning: "Dynamic, highly parameterized software is harder to understand
than more static software." (page 21)<ref name="DesignPattern1" />


"Dynamic, highly parameterized software is harder to understand
=== Aggregation vs. Acquaintance (association) of objects ===
than more static software." (Gang of Four 1995:21)


The authors further distinguish between '[[aggregation]]', where one object 'has' or 'is part of' another object
The authors further distinguish between '[[aggregation]]', where one object 'has' or 'is part of' another object
Line 62: Line 73:
aggregation and suggests much looser coupling between objects, which
aggregation and suggests much looser coupling between objects, which
can often be desirable for maximum maintainability in a design.
can often be desirable for maximum maintainability in a design.
=== Terminology: 'toolkit' for 'class library', e.g. ===


The authors employ the term 'toolkit' where others might today use 'class library',
The authors employ the term 'toolkit' where others might today use 'class library',
Line 71: Line 84:
'''toolkits''' are harder, and '''frameworks''' are the hardest to design.
'''toolkits''' are harder, and '''frameworks''' are the hardest to design.


==Case study, Chapter 2==
==Patterns covered in the book==  
 
Chapter 2 is a step-by-step case study on "the design of a 'What-You-See-Is-What-You-Get' (or 'WYSIWYG') document editor called Lexi." (pp33)
 
The chapter goes through seven problems that must be addressed in order to properly design Lexi, including any constraints that must be followed. Each problem is analyzed in-depth, and a solution are proposed. Each solution is explained in full, including with pseudo-code and UML where appropriate.
 
Finally, each solution is associated directly with one or more design patterns. It is shown how the solution is a direct implementation of that design pattern.
 
The seven problems (including their constraints) and their solutions (including the pattern(s) referenced), are as follows:
 
 
===Document Structure===
The document is "an arrangement of basic graphical elements" such as characters, lines, other shapes, etc, that "capture the total information content of the document"(pp35<!-- Should this be just one p? Or should it use "35ff"? -->). The structure of the document contains a collection of these elements, and each element can in turn be a substructure of other elements.
 
'''Problems and Constraints'''
 
#Text and graphics should be treated the same way (that is, graphics aren't a derived instance of text, nor vice versa)
#The implementation should treat complex and simple structures the same way. It should not have to know the difference between the two.
#Specific derivatives of abstract elements should have specialized analytical elements.
 
'''Solution and Pattern'''
 
A ''recursive composition'' is a hierarchial structure of elements, that builds "increasingly complex elements out of simpler ones" (pp36<!-- Should this be just one p? Or should it use "35ff"? -->). Each node in the structure knows of its own children and its parent. If an operation is to be performed on the whole structure, each node calls the operation on its children (recusively).
 
This is an implementation of a [[composite pattern]], which is a collection of nodes. The node is an [[Abstract type|abstract base class]], and derivatives can either be leaves (singular), or collections of other nodes (which in turn can contain leaves or collection-nodes). When an operation is performed on the parent, that operation is recursively passed down the hierarchy.
 
===Formatting===
Formatting differs from structure. Formatting is a method of constructing a particular instance of the document's physical structure. This includes breaking text into lines, using hyphens, adjusting for margin widths, etc.
 
'''Problems and Constraints'''
 
#Balance between (formatting) quality, speed and storage space
#Keep formatting independent (uncoupled from) the document structure.
 
'''Solution and Pattern'''
 
A ''Compositor'' class will encapsulate the algorithm used to format a composition. Compositor is a subclass of the primitive object of the document's structure. A Compositor has an associated instance of a Composition object. When a Compositor runs its Compose(), it iterates through each element of its associated Composition, and rearranges the structure by inserting Row and Column objects as needed.
 
The Compositor itself is an abstract class, allowing for derivative classes to use different formatting algorithms (such as double-spacing, wider margins, etc)
 
The [[Strategy pattern|Strategy Pattern]] is used to accomplish this goal. A Strategy is a method of encapsulating multiple algorithms to be used based on a changing context. In this case, formatting should be different, depending on if text, graphics, simple elements, etc, are being formatted.
 
===Embellishing the User Interface===
The ability to change the graphical interface that the user uses to interact with the document.
 
'''Problems and Constraints'''
 
#Demarcate a page of text with a border around the editing area
#Scroll bars that let the user view different parts of the page
#User interface objects should not know about the embellishments
#Avoid an "explosion of classes" that would be caused by subclassing for "every possible combination of embellishments" and elements (p44)
 
'''Solution and Pattern'''
 
The use of a ''transparent enclosure'' allows elements that augment the behaviour of composition to be added to a composition. These elements, such as Border and Scroller, are special subclasses of the singular element itself. This allows the composition to be augmented, effectively adding state-like elements. Since these augmentations are part of the structure, their appropriate Operation() will be called when the structure's Operation() is called. This means that the client does not need any special knowledge or interface with the structure in order to use the embellishments.
 
This is a [[Decorator pattern|Decorator]] pattern, one that adds responsibilities to an object without modifying the object itself.
 
===Supporting Multiple Look-And-Feel Standards===
 
[[Look and feel|Look-and-feel]] refers to [[Platform (computing)|platform]]-specific UI standards.  These standards "define guidelines for how applications appear and react to the user" (pp47).
 
'''Problems and Constraints'''
 
#The editor must implement standards of multiple platforms so that it is [[porting|portable]]
#Easily adapt to new and emergent standards
#Allow for run-time changing of look-and-feel (ie: No [[hard coded|hard-coding]])
#Have a set of abstract elemental subclasses for each category of elements (ScrollBar, Buttons, etc)
#Have a set of concrete subclasses for each abstract subclass that can have a different look-and-feel standard. (ScrollBar having MotifScrollBar and PresentationScrollBar for Motif and Presentation look-and-feels)
 
'''Solution and Pattern'''
 
Since object creatition of different concrete objects cannot be done at runtime, the object creation process must be abstracted. This is done with an abstract guiFactory, which takes on the responsibility of creating UI elements. The abstract guiFactory has concrete implementations, such as MotifFactory, which creates concrete elements of the appropriate type (MotifScrollBar). In this way, the program need only ask for a ScrollBar and, at run-time, it will be given the correct concrete element.
 
This is an [[Abstract factory pattern|Abstract Factory]]. A regular factory creates concrete objects of one type. An abstract factory creates concrete objects of varying types, depending on the concrete implementation of the factory itself. Its ability to focus on not just concrete objects, but entire ''families'' of concrete objects "distinguishes it from other creational patterns, which involve only one kind of product object" (pp51).
 
===Supporting Multiple Window Systems===
 
Just as look-and-feel is different across platforms, so is the method of handling [[window (computing)|windows]]. Each platform displays, lays out, handles input to and output from, and layers windows differently.
 
'''Problems and Constraints'''
 
#The document editor must run on as many of the "important and largely incompatible window systems" that exist (pp52)
#An Abstract Factory cannot be used. Due to differening standards, there will not be a common abstract class for each type of widget.
#Do not create a new, nonstandard windowing system
 
'''Solution and Pattern'''
 
It is possible to develop "our own abstract and concrete product classes", because "all window systems do generally the same thing" (pp52). Each window system provides operations for drawing primitive shapes, iconifying/de-iconfiying, resizing, and refreshing window contents.
 
An abstract base Window class can be derived to the different types of existing windows, such as application, iconified, dialog. These classes will contain operations that are associated with windows, such as reshaping, graphically refreshing, etc. Each window contains elements, whose Draw() functions are called upon by the Window's own draw-related functions.
 
In order to avoid having to create platform-specific Window subclasses for every possible platform, an interface will be used.  The Window class will implement a Window Implementation (WindowImp) abstract class. This class will then in turn be derived into multiple platform-specific implementations, each with platform-specific operations.  Hence, only one set of Window classes are needed for each type of Window, and only one set of WindowImp classes are needed for each platform (rather than the [[Cartesian product|Cartesian product]] of all available types and platforms).  In addition, adding a new window type does not require any modification of platform implementation, or vice-versa.
 
This is a [[Bridge pattern|Bridge pattern]]. Window and WindowImp are different, but related. Window deals with windowing in the program, and WindowImp deals with windowing on a platform. One of them can change without ever having to modify the other. The Bridge pattern allows these two "separate class hierachies to work together even as they evolve independently" (pp54).
 
===User Operations===
 
All actions the user can take with the document, ranging from entering text, changing formatting, quitting, saving, etc.
 
'''Problems and Constraints'''
 
#Operations must be accessed through different inputs, such as a menu option and a keyboard shortcut for the same command
#Each option has an interface, which should be modifyable
#Operations are implemented in several different classes
#In order to avoid coupling, there must not be a lot of dependencies between implementation and user interface classes.
#Undo and redo commands must be supported on most document changing operations, with no arbitrary limit on the number of levels of undo
#Functions are not viable, since they don't undo/redo easily, are not easily associated with a state, and are hard to extend or reuse.
#Menus should be treated like heirarchal composite structures. Hence, a menu is a menu item that contains menu items which may contain other menu items, etc.
 
'''Solution and Pattern'''


Each menu item, rather than being instantiated with a list of parameters, is instead done with an object. That object is a ''Command'' object.  
=== Abstract Factory ===
The [[Abstract factory pattern]] groups object factories that have a common theme.


Command is an abstract object that only has a single abstract Execute() method. Derivative objects extend the Execute() method appropriately (ie: the PasteCommand.Execute() would utilize the contents clipboard buffer). These objects can be used by widgets or buttons just as easily as they can be used by menu items.
=== Builder ===
The [[Builder pattern]] constructs complex objects by separating construction and representation.


To support undo and redo, Command is also given Unexecute() and Reversible(). In derivative classes, the former contains code that will undo that command, and the later returns a boolean value that defines if the command is undoable. Reversible() allows some commands to be non-undoable, such as a Save command.
=== Factory Method ===
The [[Factory method pattern]] creates objects without specifying the exact object to create.


All executed Commands are kept in a list with a method of keeping a "present" market directly after the most recently executed command. A request to undo will call the Command.Unexecute() directly before present, then move present back one command. Conversely, a Redo request will call Command.Execute() after present, and move present forward one.
===Prototype===
The [[Prototype pattern]] creates objects by cloning an existing object.


This Command history is an implementation of the [[Command pattern|Command]] pattern. It encapsulates requests in objects, and uses a common interface to access those requests. Thus, the client can handle different requests, and commands can be scattered  throughout the application.
=== Singleton ===
The [[Singleton pattern]] restricts object creation of a class to only one instance.


===Spelling Checking and Hyphenation===
=== Adapter ===
The [[Adapter pattern]] allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.


This is the document editor's ability to textual analyze the contents of a document. Although there are many analysis that can be performed, spell check and hyphenation-formatting are the focus.
=== Bridge ===
The [[Bridge pattern]] decouples an abstraction from its implementation so that the two can vary independently.


'''Problems and Constraints'''
=== Composite ===
The [[Composite pattern]] composes one-or-more similar objects so that they can be manipulated as one object.


#Allow for multiple ways to check spelling and identify places for hyphenation
=== Decorator ===
#Allow for expansion for future analysis (eg: word count, grammar check)
The [[Decorator pattern]] dynamically adds/overrides behaviour in an existing method of an object.
#Be able to iterate through a text's contents without access to the text's actual structure (eg: array, linked list, string)
#Allow for any manner of traversal of document (beginning to end, end to beginning, alphabetical order, etc)


'''Solution and Pattern'''
=== Façade ===
The [[Façade pattern]] provides a simplified interface to a large body of code.


Removing the integer-based index from the basic element allows for a different iteration interface to be implemented. This will require extra methods for traversal and object retrieval. These methods are put into an abstract ''Iterator'' interface. Each element then implements a derivation of the Iterator, depending on how that element keeps its list (ArrayIterator, LinkListIterator, etc).  
=== Flyweight ===
The [[Flyweight pattern]] reduces the cost of creating and manipulating a large number of similar objects.


Functions for traversal and retrieval are put into the abstract Iterator interface. Future Iterators can be derived based on the type of list they will be iterating through, such as Arrays or Linked Lists. Thus, no matter what type of indexing method any implementation of the element uses, it will have the appropriate Iterator.
=== Proxy ===
The [[Proxy pattern]] provides a placeholder for another object to control access, reduce cost, and reduce complexity.


This is an implementation of the [[Iterator pattern|Iterator]] pattern. It allows the client to traverse through any object collection, without needing to access the contents of the collection directly, or be concerned about the type of list the collection's structure uses.
=== Chain-of-responsibility ===
The [[Chain-of-responsibility pattern]] delegates a series of commands to a chain of processing objects.


Now that traversal has been handled, it is possible to analyze the elements of a structure. It is not feasible to build each type of analysis into the element structure themselves; every element would need to be coded, and much of the code would be the same for similar elements.
=== Command ===
The [[Command pattern]] creates objects which encapsulate actions and parameters.


Instead, a generic CheckMe() method is built into the element's abstract class. Each Iterator is given a reference to a specific algorithm (such as spell check, grammar check, etc). When that Iterator iterates through its collection, it calls each element's CheckMe, passing the specified algorithm. CheckMe then passes a reference to its element back to said algorithm for analysis.  
=== Interpreter ===
The [[Interpreter pattern]] implements a specialized language.


Thus, to perform a spell check, a front-to-end iterator would be given a reference to a SpellCheck object. The iterator would then access each element, executing its CheckMe() method with the SpellCheck parameter. Each CheckMe would then call the SpellCheck, passing a reference to the appropriate element.
=== Iterator ===
The [[Iterator pattern]] accesses the elements of an object sequentially without exposing its underlying representation.


In this manner, any algorithm can be used with any traversal method, without hard-code coupling one with the other. For example, Find can be used as "find next" or "find previous", depending on if a "forward" iterator was used, or a "backwards" iterator.
=== Mediator ===
The [[Mediator pattern]] allows loose coupling between classes by being the only class that has detailed knowledge of their methods.


In addition, the algorithm themselves can be responsible for dealing with different elements. For example, a SpellCheck algorithm would ignore a Graphic element, rather than having to program every Graphic-derived element to not send themselves to a SpellCheck.
=== Memento ===
The [[Memento pattern]] provides the ability to restore an object to its previous state (undo).


This is an implementation of the [[Visitor pattern|Visitor]] pattern.
=== Observer ===
The [[Observer pattern]] is a publish/subscribe pattern which allows a number of observer objects (the "subscribers") to see an event (the "published" thing to be observed).  This pattern is often, or typically, used for communications among multiple threads or processes of execution which are not otherwise synchronized with each other.


==Creational patterns, Chapter 3==  
=== State ===
These patterns have to do with class instantiation. They can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation to get the job done.
The [[State pattern]] allows an object to alter its behavior when its internal state changes.


* [[Abstract factory pattern|Abstract Factory]] groups object factories that have a common theme.
=== Strategy ===
* [[Builder pattern|Builder]] constructs complex objects by separating construction and representation.
The [[Strategy pattern]] allows one of a family of algorithms to be selected on-the-fly at runtime.
* [[Factory method pattern|Factory Method]] creates objects without specifying the exact object to create.
* [[Prototype pattern|Prototype]] creates objects by cloning an existing object.
* [[Singleton pattern|Singleton]] restricts object creation for a class to only one instance.


==Structural patterns, Chapter 4==
=== Template Method ===
These concern Class and Object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.
The [[Template method pattern]] defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
* [[Adapter pattern|Adapter]] allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
* [[Bridge pattern|Bridge]] decouples an abstraction from its implementation so that the two can vary independently.
* [[Composite pattern|Composite]] composes one-or-more similar objects so that they can be manipulated as one object.
* [[Decorator pattern|Decorator]] dynamically adds/overrides behaviour in an existing method of an object.
* [[Façade pattern|Façade]] provides a simplified interface to a large body of code.
* [[Flyweight pattern|Flyweight]] reduces the cost of creating and manipulating a large number of similar objects.
* [[Proxy pattern|Proxy]] provides a placeholder for another object to control access, reduce cost, and reduce complexity.


==Behavioral patterns, Chapter 5==
=== Visitor ===
These design patterns are about Class's objects communication. They are specifically concerned with communication between '''objects'''.
[[Visitor pattern]] separates an algorithm from an object structure by moving the hierarchy of methods into one object.
 
* [[Chain-of-responsibility pattern|Chain of responsibility]] delegates a series of commands to a chain of processing objects.
* [[Command pattern|Command]] creates objects which encapsulate actions and parameters.
* [[Interpreter pattern|Interpreter]] implements a specialized language.
* [[Iterator pattern|Iterator]] accesses the elements of an object sequentially without exposing its underlying representation.
* [[Mediator pattern|Mediator]] allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
* [[Memento pattern|Memento]] provides the ability to restore an object to its previous state (undo).
* [[Observer pattern|Observer]] is a publish/subscribe pattern which allows a number of observer objects to see an event.
* [[State pattern|State]] allows an object to alter its behavior when its internal state changes.
* [[Strategy pattern|Strategy]] allows one of a family of algorithms to be selected on-the-fly at runtime.
* [[Template method pattern|Template method]] defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
* [[Visitor pattern|Visitor]] separates an algorithm from an object structure by moving the hierarchy of methods into one object.
 
==Related articles==
* [[Design pattern (computer science)]]
* [[Enterprise Integration Patterns]]


==External links==
==External links==
* [http://www.awprofessional.com/title/0201633612] Addison-Wesley, Publisher  
* [http://www.awprofessional.com/title/0201633612 Design Patterns: Elements of Reusable Object-Oriented Software] Addison-Wesley, Publisher  
* [http://www.eden-study.org/precise_and_formal Formal And Precise Software Pattern Representation Languages] A bibliography
* [http://tal.forum2.org/hatching Pattern Hatching] by John Vlissides (one of the ''gang of four'')
* [http://tal.forum2.org/hatching Pattern Hatching]
* [http://www.eden-study.org/lepus/ LePUS] A formal language for describing and reasoning about design patterns
* [http://www.felix-colibri.com/ Felix COlibri] pattern source code: the 24 gof patterns, the gof LEXI editor, Bridge and Abstract Factory
* [http://c2.com/cgi/wiki?AntiPattern Anti Pattern] Anti Pattern
* [http://c2.com/cgi/wiki?AntiPattern Anti Pattern] Anti Pattern


{{Design Patterns Patterns}}
==References==
 
<references />
[[Category:Computer books]]
[[Category:Software design patterns|*Design patterns]]
[[Category:1994 books]]
 
[[bs:Design Patterns (knjiga)]]
[[de:Viererbande (Softwareentwicklung)]]
[[fr:Patron de conception]]
[[ko:디자인 패턴 (책)]]
[[it:Design Patterns]]
[[vi:Design Patterns]]
[[zh:设计范例]]
[[es:Design Patterns]]

Latest revision as of 20:48, 15 December 2020

This article is developing and not approved.
Main Article
Discussion
Related Articles  [?]
Bibliography  [?]
External Links  [?]
Citable Version  [?]
 
This editable Main Article is under development and subject to a disclaimer.

Design Patterns: Elements of Reusable Object-Oriented Software (ISBN 0-201-63361-2) is a landmark book, first published in 1995, that recommends a set of best practices for object-oriented design and catalogs a variety of object-oriented software architectures illustrated in C++ and Smalltalk[1]. In its 36th printing as of April 2007, the book has been translated into more than a dozen languages and has been highly regarded in the field of software engineering. However, the book makes for such dense reading (even for experienced programmers) that it has been superseded, in practice, by a spate of more recent, accessibly-written books despite being regarded as an important source for object-oriented design theory.

The book's authors (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides) are commonly spoken of as the gang of four due to difficulties in speaking or remembering all their names at once.

Chapter 1 summary: Overview and Philosophy

Chapter 1 is a discussion of object-oriented design techniques, based on the authors' experience, which they believe would lead to good object-oriented software design.

When to use Interfaces vs. Inheritance

The authors claim the following as advantages of interfaces over inheritance:

  • clients remain unaware of the specific types of objects they use, as long as the object adheres to the interface
  • clients remain unaware of the classes that implement these objects; clients only know about the abstract class(es) defining the interface

Inheritance as White-box Software Engineering, Object Composition as Black-box SE

The authors refer to inheritance as white-box reuse, with white-box referring to visibility, because the internals of parent classes are often visible to subclasses. In contrast, the authors refer to object composition (in which objects with well-defined interfaces are used dynamically at runtime by objects obtaining references to other objects) as black-box reuse because no internal details of composed objects need be visible in the code using them.

Inheritance overused; when and how to use it; pitfalls

The authors discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance (page 20)[1]. The danger is stated as follows:

"Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". (page 19)[1]

They warn that the implementation of a subclass can become so bound up with the implementation of its parent class that any change in the parent's implementation will force the subclass to change. They say that a way to avoid this is to inherit only from abstract classes--but then, they point out that there is minimal code reuse.

They recommend using inheritance mainly when adding to the functionality of existing components, reusing most of the old code and adding relatively small amounts of new code.

Delegates as run-time linking

To the authors, 'delegation' is an extreme form of object composition that can always be used to replace inheritance. Delegation involves two objects: a 'sender' passes itself to a 'delegate' to let the delegate refer to the receiver. Thus the link between two parts of a system are established only at runtime, not at compile-time. The Callback article has more information about delegation.

Generics (Templates in C++)

The authors also discuss so-called parameterized types, which are also known as generics (Ada, Eiffel, Java, C#) or templates (C++). These allow a type to be defined without specifying all the other types it uses--the unspecified types are supplied as 'parameters' at the point of use.

Warning about Delegates and Generics

The authors admit that delegation and parameterization are very powerful but add a warning: "Dynamic, highly parameterized software is harder to understand than more static software." (page 21)[1]

Aggregation vs. Acquaintance (association) of objects

The authors further distinguish between 'aggregation', where one object 'has' or 'is part of' another object (implying that an aggregate object and its owner have identical lifetimes) and acquaintance, where one object merely 'knows of' another object. Sometimes acquaintance is called 'association' or the 'using' relationship. Acquaintance objects may request operations of each other, but they aren't responsible for each other. Acquaintance is a weaker relationship than aggregation and suggests much looser coupling between objects, which can often be desirable for maximum maintainability in a design.

Terminology: 'toolkit' for 'class library', e.g.

The authors employ the term 'toolkit' where others might today use 'class library', as in C# or Java. In their parlance, toolkits are the object-oriented equivalent of subroutine libraries, whereas a 'framework' is a set of cooperating classes that make up a reusable design for a specific class of software. They state that applications are hard to design, toolkits are harder, and frameworks are the hardest to design.

Patterns covered in the book

Abstract Factory

The Abstract factory pattern groups object factories that have a common theme.

Builder

The Builder pattern constructs complex objects by separating construction and representation.

Factory Method

The Factory method pattern creates objects without specifying the exact object to create.

Prototype

The Prototype pattern creates objects by cloning an existing object.

Singleton

The Singleton pattern restricts object creation of a class to only one instance.

Adapter

The Adapter pattern allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.

Bridge

The Bridge pattern decouples an abstraction from its implementation so that the two can vary independently.

Composite

The Composite pattern composes one-or-more similar objects so that they can be manipulated as one object.

Decorator

The Decorator pattern dynamically adds/overrides behaviour in an existing method of an object.

Façade

The Façade pattern provides a simplified interface to a large body of code.

Flyweight

The Flyweight pattern reduces the cost of creating and manipulating a large number of similar objects.

Proxy

The Proxy pattern provides a placeholder for another object to control access, reduce cost, and reduce complexity.

Chain-of-responsibility

The Chain-of-responsibility pattern delegates a series of commands to a chain of processing objects.

Command

The Command pattern creates objects which encapsulate actions and parameters.

Interpreter

The Interpreter pattern implements a specialized language.

Iterator

The Iterator pattern accesses the elements of an object sequentially without exposing its underlying representation.

Mediator

The Mediator pattern allows loose coupling between classes by being the only class that has detailed knowledge of their methods.

Memento

The Memento pattern provides the ability to restore an object to its previous state (undo).

Observer

The Observer pattern is a publish/subscribe pattern which allows a number of observer objects (the "subscribers") to see an event (the "published" thing to be observed). This pattern is often, or typically, used for communications among multiple threads or processes of execution which are not otherwise synchronized with each other.

State

The State pattern allows an object to alter its behavior when its internal state changes.

Strategy

The Strategy pattern allows one of a family of algorithms to be selected on-the-fly at runtime.

Template Method

The Template method pattern defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.

Visitor

Visitor pattern separates an algorithm from an object structure by moving the hierarchy of methods into one object.

External links

References

  1. 1.0 1.1 1.2 1.3 1.4 1.5 Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley (2007). Retrieved on 2007-05-24.