Design Patterns
Encyclopedia
Design Patterns: Elements of Reusable Object-Oriented Software 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
with a foreword by Grady Booch
. The authors are often referred to as the Gang of Four, or GoF. 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 23 classic software design pattern
s. The book includes examples in C++
and Smalltalk
.
The original publication date of the book was October 21, 1994 with a 1995 copyright, and as of July 2010, the book was in its 38th printing. The book was first made available to the public at OOPSLA
meeting held in Portland, Oregon in October 1994. 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 authors claim the following as advantages of interfaces
over implementation:
Use of an interface also leads to dynamic binding
and polymorphism
, which is consequentially important to object-oriented programming.
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.
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:
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. Furthermore, they claim that a way to avoid this is to inherit only from abstract classes—but then, they point out that there is minimal code reuse.
Using inheritance is recommended mainly when adding to the functionality of existing components, reusing most of the old code and adding relatively small amounts of new code.
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 sender. 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.
The authors also discuss so-called parameterized types, which are also known as generics
(Ada, Eiffel, Java
, C#, VB.NET, and Delphi) or templates (C++). These allow any 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 admit that delegation and parameterization are very powerful but add a warning:
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.
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.
' (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 solutions are proposed. Each solution is explained in full, including pseudo-code and Unified Modeling Language
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:
Problems and Constraints
Solution and Pattern
A recursive composition is a hierarchical structure of elements, that builds "increasingly complex elements out of simpler ones" (pp36). 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 (recursively).
This is an implementation of the composite pattern
, which is a collection of nodes. The node is an 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.
Problems and Constraints
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
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
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 whether text, graphics, simple elements, etc., are being formatted.
Problems and Constraints
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
This is a Decorator pattern
, one that adds responsibilities to an object without modifying the object itself.
refers to platform
-specific UI standards. These standards "define guidelines for how applications appear and react to the user" (pp47).
Problems and Constraints
Solution and Pattern
Since object creation 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
. 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).
. Each platform displays, lays out, handles input to and output from, and layers windows differently.
Problems and Constraints
Solution and Pattern
It is possible to develop "our own abstract and concrete product classes", because "all window systems do generally the same thing" (p. 52). Each window system provides operations for drawing primitive shapes, iconifying/de-iconifying, resizing, and refreshing window contents.
An abstract base
In order to avoid having to create platform-specific Window subclasses for every possible platform, an interface will be used. The
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
.
Problems and Constraints
Solution and Pattern
Each menu item, rather than being instantiated with a list of parameters, is instead done with a Command object.
Command is an abstract object that only has a single abstract
To support undo and redo,
All executed
This
. 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.
Problems and Constraints
Solution and Pattern
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
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.
This is an implementation of the 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.
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.
Instead, a generic
Thus, to perform a spell check, a front-to-end iterator would be given a reference to a
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.
In addition, the algorithm themselves can be responsible for dealing with different elements. For example, a
rather than having you instantiate objects directly. This
gives your program more flexibility in deciding which
objects need to be created for a given case.
Software engineering
Software Engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software...
book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma
Erich Gamma
Erich Gamma is Swiss computer scientist and co-author of the influential Software engineering textbook, Design Patterns: Elements of Reusable Object-Oriented Software. He co-wrote the JUnit software testing framework with Kent Beck and led the design of the Eclipse platform's Java Development Tools...
, Richard Helm, Ralph Johnson and John Vlissides
John Vlissides
John Matthew Vlissides was a software scientist known mainly as one of the four authors of the book Design Patterns: Elements of Reusable Object-Oriented Software...
with a foreword by Grady Booch
Grady Booch
Grady Booch is an American software engineer. Booch is best known for developing the Unified Modeling Language with Ivar Jacobson and James Rumbaugh. Grady is recognized internationally for his innovative work in software architecture, software engineering, and collaborative development environments...
. The authors are often referred to as the Gang of Four, or GoF. 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 23 classic software design pattern
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...
s. The book includes examples in C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
and Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
.
The original publication date of the book was October 21, 1994 with a 1995 copyright, and as of July 2010, the book was in its 38th printing. The book was first made available to the public at OOPSLA
OOPSLA
OOPSLA is an annual ACM research conference. OOPSLA mainly takes place in the United States, while the sister conference of OOPSLA, ECOOP, is typically held in Europe...
meeting held in Portland, Oregon in October 1994. 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.
Introduction, Chapter 1
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:- "Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)
- "Favor 'object compositionObject compositionIn computer science, object composition is a way to combine simple objects or data types into more complex ones...
' over 'class inheritanceInheritance (computer science)In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
'." (Gang of Four 1995:20)
The authors claim the following as advantages of interfaces
Interface (computer science)
In the field of computer science, an interface is a tool and concept that refers to a point of interaction between components, and is applicable at the level of both hardware and software...
over implementation:
- 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
Use of an interface also leads to dynamic binding
Dynamic dispatch
In computer science, dynamic dispatch is the process of mapping a message to a specific sequence of code at runtime. This is done to support the cases where the appropriate method can't be determined at compile-time...
and polymorphism
Polymorphism in object-oriented programming
Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability to create a variable, a function, or an object that has more than one form. The word derives from the Greek "πολυμορφισμός" meaning "having multiple forms"...
, which is consequentially important to object-oriented programming.
The authors refer to inheritance
Inheritance (object-oriented programming)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
as white-box reuse
White box (software engineering)
In software engineering white box, in contrast to a black box, is a subsystem whose internals can be viewed, but usually cannot be altered. This is useful during white box testing, where a system is examined to make sure that it fulfills its requirements....
, 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
Object composition
In computer science, object composition is a way to combine simple objects or data types into more complex ones...
(in which objects with well-defined interfaces are used dynamically at runtime by objects obtaining references to
other objects) as black-box reuse
Black box
A black box is a device, object, or system whose inner workings are unknown; only the input, transfer, and output are known characteristics.The term black box can also refer to:-In science and technology:*Black box theory, a philosophical theory...
because no internal details of 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:
- "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)
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. Furthermore, they claim that a way to avoid this is to inherit only from abstract classes—but then, they point out that there is minimal code reuse.
Using inheritance is recommended mainly when adding to the functionality of existing components, reusing most of the old code and adding relatively small amounts of new code.
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 sender. Thus the link between two parts of a system are established only at runtime, not at compile-time. The Callback
Callback (computer science)
In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine defined in a higher-level layer....
article has more information about delegation.
The authors also discuss so-called parameterized types, which are also known as generics
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
(Ada, Eiffel, Java
Generics in Java
Generics are a facility of generic programming that was added to the Java programming language in 2004 as part of J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety." A common use of this feature is when using a Java Collection...
, C#, VB.NET, and Delphi) or templates (C++). These allow any 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 admit that delegation and parameterization are very powerful but add a warning:
- "Dynamic, highly parameterized software is harder to understand and build 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 (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.
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
Software framework
In computer programming, a software framework is an abstraction in which software providing generic functionality can be selectively changed by user code, thus providing application specific software...
' 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.
Case study, Chapter 2
Chapter 2 is a step-by-step case study on "the design of a 'What-You-See-Is-What-You-GetWYSIWYG
WYSIWYG is an acronym for What You See Is What You Get. The term is used in computing to describe a system in which content displayed onscreen during editing appears in a form closely corresponding to its appearance when printed or displayed as a finished product...
' (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 solutions are proposed. Each solution is explained in full, including pseudo-code and Unified Modeling Language
Unified Modeling Language
Unified Modeling Language is a standardized general-purpose modeling language in the field of object-oriented software engineering. The standard is managed, and was created, by the Object Management Group...
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). 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 hierarchical structure of elements, that builds "increasingly complex elements out of simpler ones" (pp36). 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 (recursively).
This is an implementation of the composite pattern
Composite pattern
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent...
, which is a collection of nodes. The node is an abstract base class
Abstract type
In programming languages, an abstract type is a type in a nominative type system which cannot be instantiated. An abstract type may have no implementation, or an incomplete implementation...
, 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
In computer programming, the strategy pattern is a particular software design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable...
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 whether 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
In object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically.-Introduction:...
, one that adds responsibilities to an object without modifying the object itself.
Supporting Multiple Look-And-Feel Standards
Look-and-feelLook and feel
In software design, look and feel is a term used in respect of a graphical user interface and comprises aspects of its design, including elements such as colors, shapes, layout, and typefaces , as well as the behavior of dynamic elements such as buttons, boxes, and menus...
refers to platform
Platform (computing)
A computing platform includes some sort of hardware architecture and a software framework , where the combination allows software, particularly application software, to run...
-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 portablePortingIn computer science, porting is the process of adapting software so that an executable program can be created for a computing environment that is different from the one for which it was originally designed...
- Easily adapt to new and emergent standards
- Allow for run-time changing of look-and-feel (i.e.: No 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 creation 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
Abstract factory pattern
The abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the...
. 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 windowsWindow (computing)
In computing, a window is a visual area containing some kind of user interface. It usually has a rectangular shape that can overlap with the area of other 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 many of the "important and largely incompatible window systems" that exist (p. 52)
- An Abstract Factory cannot be used. Due to differing 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" (p. 52). Each window system provides operations for drawing primitive shapes, iconifying/de-iconifying, 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 productCartesian product
In mathematics, a Cartesian product is a construction to build a new set out of a number of given sets. Each member of the Cartesian product corresponds to the selection of one element each in every one of those sets...
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
The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently"...
.
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 hierarchies to work together even as they evolve independently" (p. 54).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 modifiable
- 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 hierarchical 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 a Command object.
Command is an abstract object that only has a single abstract
Execute
method. Derivative objects extend the Execute
method appropriately (i.e., the PasteCommand.Execute
would utilize the content's clipboard buffer). These objects can be used by widgets or buttons just as easily as they can be used by menu items.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 latter returns a boolean value that defines if the command is undoable. Reversible
allows some commands to be non-undoable, such as a Save command.All executed
Commands
are kept in a list with a method of keeping a "present" marker 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.This
Command
history is an implementation of the Command patternCommand pattern
In object-oriented programming, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time...
. 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.
Spell Check and Hyphenation
This is the document editor's ability to textually analyze the contents of a document. Although there are many analyses that can be performed, spell check and hyphenation-formatting are the focus.Problems and Constraints
- Allow for multiple ways to check spelling and identify places for hyphenation
- Allow for expansion for future analysis (e.g., word count, grammar check)
- Be able to iterate through a text's contents without access to the text's actual structure (e.g., array, linked list, string)
- Allow for any manner of traversal of document (beginning to end, end to beginning, alphabetical order, etc.)
Solution and Pattern
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.).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.
This is an implementation of the Iterator pattern
Iterator pattern
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements...
. 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.
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.
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.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.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.
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
.Creational patterns
Creational patterns are ones that create objects for you,rather than having you instantiate objects directly. This
gives your program more flexibility in deciding which
objects need to be created for a given case.
- Abstract FactoryAbstract factory patternThe abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the...
groups object factories that have a common theme. - BuilderBuilder patternThe builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects...
constructs complex objects by separating construction and representation. - Factory MethodFactory method patternThe factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects without specifying the exact class of object that will be created.The creation of an object often requires complex...
creates objects without specifying the exact class to create. - PrototypePrototype patternThe prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects...
creates objects by cloning an existing object. - SingletonSingleton patternIn software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system...
restricts object creation for a class to only one instance.
Structural patterns
These concern class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.- AdapterAdapter patternIn computer programming, the adapter pattern is a design pattern that translates one interface for a class into a compatible interface...
allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class. - BridgeBridge patternThe bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently"...
decouples an abstraction from its implementation so that the two can vary independently. - CompositeComposite patternIn software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent...
composes zero-or-more similar objects so that they can be manipulated as one object. - DecoratorDecorator patternIn object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically.-Introduction:...
dynamically adds/overrides behaviour in an existing method of an object. - FacadeFaçade patternThe facade pattern is a software engineering design pattern commonly used with Object-oriented programming. The name is by analogy to an architectural facade....
provides a simplified interface to a large body of code. - FlyweightFlyweight patternFlyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. The term is named...
reduces the cost of creating and manipulating a large number of similar objects. - ProxyProxy patternIn computer programming, the proxy pattern is a software design pattern.A proxy, in its most general form, is a class functioning as an interface to something else...
provides a placeholder for another object to control access, reduce cost, and reduce complexity.
Behavioral patterns
Most of these design patterns are specifically concerned with communication between objects.- Chain of responsibilityChain-of-responsibility patternIn Object Oriented Design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains a set of logic that describes the types of command objects that it can handle, and how to pass off those...
delegates commands to a chain of processing objects. - CommandCommand patternIn object-oriented programming, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time...
creates objects which encapsulate actions and parameters. - InterpreterInterpreter patternIn computer programming, the interpreter pattern is a design pattern. The interpreter pattern specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol in a specialized computer language...
implements a specialized language. - IteratorIterator patternIn object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements...
accesses the elements of an object sequentially without exposing its underlying representation. - MediatorMediator patternThe mediator pattern, one of the 23 design patterns described in Design Patterns: Elements of Reusable Object-Oriented Software, provides a unified interface to a set of interfaces in a subsystem. This pattern is considered to be a behavioral pattern due to the way it can alter the program's...
allows loose couplingLoose couplingIn computing and systems design a loosely coupled system is one where each of its components has, or makes use of, little or no knowledge of the definitions of other separate components. The notion was introduced into organizational studies by Karl Weick...
between classes by being the only class that has detailed knowledge of their methods. - MementoMemento patternThe memento pattern is a software design pattern that provides the ability to restore an object to its previous state .The memento pattern is implemented with two objects: the originator and a caretaker. The originator is some object that has an internal state. The caretaker is going to do...
provides the ability to restore an object to its previous state (undo). - ObserverObserver patternThe observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods...
is a publish/subscribe pattern which allows a number of observer objects to see an event. - StateState patternThe state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at...
allows an object to alter its behavior when its internal state changes. - StrategyStrategy patternIn computer programming, the strategy pattern is a particular software design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable...
allows one of a family of algorithms to be selected on-the-fly at runtime. - Template methodTemplate method patternIn software engineering, the template method pattern is a design pattern.It is a behavioral pattern, and is unrelated to C++ templates.-Introduction:A template method defines the program skeleton of an algorithm...
defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior. - VisitorVisitor patternIn object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those...
separates an algorithm from an object structure by moving the hierarchy of methods into one object.
See also
- Design pattern (computer science)Design pattern (computer science)In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...
- Enterprise Integration PatternsEnterprise Integration PatternsEnterprise Integration Patterns is a book by Gregor Hohpe and Bobby Woolf and describes a number of design patterns for the use of enterprise application integration and message-oriented middleware....
- GRASP (object-oriented design)
- Pedagogical patternsPedagogical patternsPedagogical Patterns are high-level patterns that have been recognized in many areas of training and pedagogy such as group work, software design, human computer interaction, education and others. The concept is an extension of pattern languages...