Software Design Patterns Tutorial

Design Patterns:
Elements of Reusable Object-Oriented Software
AuthorThe 'Gang of Four':
Erich Gamma,
Richard Helm,
Ralph Johnson,
John Vlissides
CountryUnited States
SubjectDesign patterns, software engineering, object-oriented programming
PublisherAddison-Wesley
1994
Pages395
ISBN0-201-63361-2
OCLC31171684
005.1/2 20
LC ClassQA76.64 .D47 1995

Design Patterns: Elements of Reusable Object-Oriented Software (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword by Grady Booch. 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 patterns. The book includes examples in C++ and Smalltalk.

It has been 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 are often referred to as the Gang of Four (GoF).[1]

  • 3Case study, Chapter 2
  • 4Patterns by Type

History[edit]

If you're interested in reading about the other design patterns, Wikipedia's Design Patterns page has a plethora of information. If that's not enough, you can always check out Design Patterns: Elements of Reusable Object-Oriented Software, which is considered to be one of the best design pattern books available. Design Patterns in Java Tutorial - Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that sof. Knit Design Studio is another free pattern design software for Windows. Using it, you can create simple knitting patterns and graphs. A pattern of almost any size can be created in it as you can manually define the size of the canvas at the time of project creation. Design Patterns: Elements of Reusable Object-Oriented Software 5 Preface to CD As we were writing Design Patterns, we knew the patterns we weredescribing had value because they had proven themselves in manydifferent contexts.

The book started at a birds of a feather (BoF) session at OOPSLA '90, 'Towards an Architecture Handbook', run by Bruce Anderson, where Erich Gamma and Richard Helm met and discovered their common interest. They were later joined by Ralph Johnson and John Vlissides.[2] The original publication date of the book was October 21, 1994 with a 1995 copyright, hence it is often cited with a 1995-year, despite being published in 1994. The book was first made available to the public at the OOPSLA meeting held in Portland, Oregon, in October 1994.In 2005 the ACM SIGPLAN awarded that year's Programming Languages Achievement Award to the authors, in recognition of the impact of their work 'on programming practice and programming language design'.[3] As of March 2012, the book was in its 40th printing.

Introduction, Chapter 1[edit]

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)
  • Composition over inheritance: 'Favor 'object composition' over 'class inheritance'.' (Gang of Four 1995:20)

The authors claim the following as advantages of interfaces 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 and polymorphism, which are central features of object-oriented programming.

The authors refer to inheritance as white-box reuse, withwhite-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 toother 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:

'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 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:

'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' 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[edit]

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.' (pp.33)

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 a slightly modified version of Object Modeling Technique 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[edit]

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'(pp.35). 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

  1. Text and graphics should be treated the same way (that is, graphics aren't a derived instance of text, nor vice versa)
  2. The implementation should treat complex and simple structures the same way. It should not have to know the difference between the two.
  3. 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' (pp.36). 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.

Formatting[edit]

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

  1. Balance between (formatting) quality, speed and storage space
  2. 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 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[edit]

The ability to change the graphical interface that the user uses to interact with the document.

Problems and Constraints

  1. Demarcate a page of text with a border around the editing area
  2. Scroll bars that let the user view different parts of the page
  3. User interface objects should not know about the embellishments
  4. Avoid an 'explosion of classes' that would be caused by subclassing for 'every possible combination of embellishments' and elements (p.44)

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, one that adds responsibilities to an object without modifying the object itself.

Supporting Multiple Look-And-Feel Standards[edit]

Look-and-feel refers to platform-specific UI standards. These standards 'define guidelines for how applications appear and react to the user' (pp.47).

Problems and Constraints

  1. The editor must implement standards of multiple platforms so that it is portable
  2. Easily adapt to new and emergent standards
  3. Allow for run-time changing of look-and-feel (i.e.: No hard-coding)
  4. Have a set of abstract elemental subclasses for each category of elements (ScrollBar, Buttons, etc.)
  5. 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. 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' (pp.51).

Supporting Multiple Window Systems[edit]

Just as look-and-feel is different across platforms, so is the method of handling windows. Each platform displays, lays out, handles input to and output from, and layers windows differently.

Problems and Constraints

  1. The document editor must run on many of the 'important and largely incompatible window systems' that exist (p.52)
  2. An Abstract Factory cannot be used. Due to differing standards, there will not be a common abstract class for each type of widget.
  3. Do not create a new, nonstandard windowing system

Solution and Pattern

Software Design Patterns Pdf

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. 2006 honda crv owner manual. 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 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. 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[edit]

All actions the user can take with the document, ranging from entering text, changing formatting, quitting, saving, etc.

Problems and Constraints

  1. Operations must be accessed through different inputs, such as a menu option and a keyboard shortcut for the same command
  2. Each option has an interface, which should be modifiable
  3. Operations are implemented in several different classes
  4. In order to avoid coupling, there must not be a lot of dependencies between implementation and user interface classes.
  5. Undo and redo commands must be supported on most document changing operations, with no arbitrary limit on the number of levels of undo
  6. 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.
  7. 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 approach is an implementation of the 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.

Spell Check and Hyphenation[edit]

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

  1. Allow for multiple ways to check spelling and identify places for hyphenation
  2. Allow for expansion for future analysis (e.g., word count, grammar check)
  3. Be able to iterate through a text's contents without access to the text's actual structure (e.g., array, linked list, string)
  4. 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. 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 algorithms 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.

Patterns by Type[edit]

Creational[edit]

Creational patterns are ones that create objects, rather than having to instantiate objects directly. This gives the program more flexibility in deciding which objects need to be created for a given case.

  • Abstract factory groups object factories that have a common theme.
  • Builder constructs complex objects by separating construction and representation.
  • Factory method creates objects without specifying the exact class to create.
  • Prototype creates objects by cloning an existing object.
  • Singleton restricts object creation for a class to only one instance.

Structural[edit]

These concern class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.

  • Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
  • Bridge decouples an abstraction from its implementation so that the two can vary independently.
  • Composite composes zero-or-more similar objects so that they can be manipulated as one object.
  • Decorator dynamically adds/overrides behaviour in an existing method of an object.
  • Facade provides a simplified interface to a large body of code.
  • Flyweight reduces the cost of creating and manipulating a large number of similar objects.
  • Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.

Behavioral[edit]

Most of these design patterns are specifically concerned with communication between objects.

  • Chain of responsibility delegates commands to a chain of processing objects.
  • Command creates objects which encapsulate actions and parameters.
  • Interpreter implements a specialized language.
  • Iterator accesses the elements of an object sequentially without exposing its underlying representation.
  • Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
  • Memento provides the ability to restore an object to its previous state (undo).
  • Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.
  • State allows an object to alter its behavior when its internal state changes.
  • Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.
  • Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
  • Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object.

Criticism[edit]

Criticism has been directed at the concept of software design patterns generally, and at Design Patterns specifically. A primary criticism of Design Patterns is that its patterns are simply workarounds for missing features in C++, replacing elegant abstract features with lengthy concrete patterns, essentially becoming a 'human compiler' or 'generating by hand the expansions of some macro'.[4]Peter Norvig demonstrates that 16 out of the 23 patterns in Design Patterns are simplified or eliminated (via direct language support) in Lisp or Dylan.[5] Related observations were made by Hannemann and Kiczales who implemented several of the 23 design patterns using an aspect-oriented programming language (AspectJ) and showed that code-level dependencies were removed from the implementations of 17 of the 23 design patterns and that aspect-oriented programming could simplify the implementations of design patterns.[6]

Paul Graham wrote:[4]

When I see patterns in my programs, I consider it a sign of trouble. The shape of a program should reflect only the problem it needs to solve. Any other regularity in the code is a sign, to me at least, that I'm using abstractions that aren't powerful enough-- often that I'm generating by hand the expansions of some macro that I need to write.

There has also been humorous criticism, such as a show trial at OOPSLA '99 on 3 November 1999,[7][8][a] and a parody of the format, by Jim Coplien, entitled 'Kansas City Air Conditioner'.

In an interview with InformIT in 2009, Erich Gamma stated that the book authors had a discussion in 2005 on how they would have refactored the book and concluded that they would have recategorized some patterns, added a few additional ones and removed one of them (Singleton) altogether.[9]

See also[edit]

Notes[edit]

  1. ^Presiding Magistrate Neil Harrison, Head Prosecutor Kent Beck, Defending Barrister Martin Fowler, Court Baliff Brian Foote; Richard Helm submitted a confession, while the rest stood trial.

References[edit]

  1. ^Gang Of Four, Content Creation Wiki for People Projects And Patterns in Software Development.
  2. ^Richard Helm
  3. ^SIGPLAN FY '05 Annual Report
  4. ^ abGraham, Paul (2002). Revenge of the Nerds. Retrieved 2012-08-11.
  5. ^Norvig, Peter (1998). Design Patterns in Dynamic Languages.
  6. ^Hannemann, Jan (2002). Design pattern implementation in Java and AspectJ.
  7. ^Indictment
  8. ^The Show Trial of the Gang-of-Four, Brian Foote
  9. ^Gamma, Erich; Helm, Richard; Johnson, Ralph (2009-10-22). 'Design Patterns 15 Years Later: An Interview with Erich Gamma, Richard Helm, and Ralph Johnson'. InformIT (Interview). Interviewed by Larry O'Brien. Archived from the original on 2019-02-20. Retrieved 2019-09-01.
Retrieved from 'https://en.wikipedia.org/w/index.php?title=Design_Patterns&oldid=918419907'

In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.

Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Patterns that imply mutable state may be unsuited for functional programming languages, some patterns can be rendered unnecessary in languages that have built-in support for solving the problem they are trying to solve, and object-oriented patterns are not necessarily suitable for non-object-oriented languages.

Design patterns may be viewed as a structured approach to computer programming intermediate between the levels of a programming paradigm and a concrete algorithm.

Software Design Patterns Functional Programming

  • 3Structure
  • 4Classification and list

History[edit]

Patterns originated as an architectural concept by Christopher Alexander (1977/78). In 1987, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming – specifically pattern languages – and presented their results at the OOPSLA conference that year.[1][2] In the following years, Beck, Cunningham and others followed up on this work.

Design patterns gained popularity in computer science after the book Design Patterns: Elements of Reusable Object-Oriented Software was published in 1994 by the so-called 'Gang of Four' (Gamma et al.), which is frequently abbreviated as 'GoF'. That same year, the first Pattern Languages of Programming Conference was held, and the following year the Portland Pattern Repository was set up for documentation of design patterns. The scope of the term remains a matter of dispute. Notable books in the design pattern genre include:

  • Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN978-0-201-63361-0.
  • Brinch Hansen, Per (1995). Studies in Computational Science: Parallel Programming Paradigms. Prentice Hall. ISBN978-0-13-439324-7.
  • Buschmann, Frank; Meunier, Regine; Rohnert, Hans; Sommerlad, Peter (1996). Pattern-Oriented Software Architecture, Volume 1: A System of Patterns. John Wiley & Sons. ISBN978-0-471-95869-7.
  • Beck, Kent (1997). Smalltalk Best Practice Patterns. Prentice Hall. ISBN978-0134769042.
  • Schmidt, Douglas C.; Stal, Michael; Rohnert, Hans; Buschmann, Frank (2000). Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects. John Wiley & Sons. ISBN978-0-471-60695-6.
  • Fowler, Martin (2002). Patterns of Enterprise Application Architecture. Addison-Wesley. ISBN978-0-321-12742-6.
  • Hohpe, Gregor; Woolf, Bobby (2003). Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions. Addison-Wesley. ISBN978-0-321-20068-6.
  • Freeman, Eric T; Robson, Elisabeth; Bates, Bert; Sierra, Kathy (2004). Head First Design Patterns. O'Reilly Media. ISBN978-0-596-00712-6.

Although design patterns have been applied practically for a long time, formalization of the concept of design patterns languished for several years.[3]

Practice[edit]

Design patterns can speed up the development process by providing tested, proven development paradigms.[4] Effective software design requires considering issues that may not become visible until later in the implementation. Freshly written code can often have hidden subtle issues that take time to be detected, issues that sometimes can cause major problems down the road. Reusing design patterns helps to prevent such subtle issues[citation needed], and it also improves code readability for coders and architects who are familiar with the patterns.

In order to achieve flexibility, design patterns usually introduce additional levels of indirection, which in some cases may complicate the resulting designs and hurt application performance.

By definition, a pattern must be programmed anew into each application that uses it. Since some authors see this as a step backward from software reuse as provided by components, researchers have worked to turn patterns into components. Meyer and Arnout were able to provide full or partial componentization of two-thirds of the patterns they attempted.[5]

Software design techniques are difficult to apply to a broader range of problems.[citation needed] Design patterns provide general solutions, documented in a format that does not require specifics tied to a particular problem.

Structure[edit]

Design patterns are composed of several sections (see § Documentation below). Of particular interest are the Structure, Participants, and Collaboration sections. These sections describe a design motif: a prototypical micro-architecture that developers copy and adapt to their particular designs to solve the recurrent problem described by the design pattern. A micro-architecture is a set of program constituents (e.g., classes, methods..) and their relationships. Developers use the design pattern by introducing in their designs this prototypical micro-architecture, which means that micro-architectures in their designs will have structure and organization similar to the chosen design motif.

Domain-specific patterns[edit]

Efforts have also been made to codify design patterns in particular domains, including use of existing design patterns as well as domain specific design patterns. Examples include user interface design patterns,[6]information visualization,[7] secure design,[8] 'secure usability',[9] Web design [10] and business model design.[11]

The annual Pattern Languages of Programming Conference proceedings [12] include many examples of domain-specific patterns.

Software Design Patterns Tutorial C#

Classification and list[edit]

Design patterns were originally grouped into the categories: creational patterns, structural patterns, and behavioral patterns, and described using the concepts of delegation, aggregation, and consultation. For further background on object-oriented design, see coupling and cohesion, inheritance, interface, and polymorphism. Another classification has also introduced the notion of architectural design pattern that may be applied at the architecture level of the software such as the Model–View–Controller pattern.

Creational patterns[edit]

NameDescriptionIn Design PatternsIn Code Complete[13]Other
Abstract factoryProvide an interface for creating families of related or dependent objects without specifying their concrete classes.YesYesN/A
BuilderSeparate the construction of a complex object from its representation, allowing the same construction process to create various representations.YesNoN/A
Dependency InjectionA class accepts the objects it requires from an injector instead of creating the objects directly.NoNoN/A
Factory methodDefine an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.YesYesN/A
Lazy initializationTactic 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.NoNoPoEAA[14]
MultitonEnsure a class has only named instances, and provide a global point of access to them.NoNoN/A
Object poolAvoid 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.NoNoN/A
PrototypeSpecify 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.YesNoN/A
Resource acquisition is initialization (RAII)Ensure that resources are properly released by tying them to the lifespan of suitable objects.NoNoN/A
SingletonEnsure a class has only one instance, and provide a global point of access to it.YesYesN/A

Structural patterns[edit]

NameDescriptionIn Design PatternsIn Code Complete[13]Other
Adapter, Wrapper, or TranslatorConvert 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.YesYesN/A
BridgeDecouple an abstraction from its implementation allowing the two to vary independently.YesYesN/A
CompositeCompose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.YesYesN/A
DecoratorAttach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.YesYesN/A
Extension objectAdding functionality to a hierarchy without changing the hierarchy.NoNoAgile Software Development, Principles, Patterns, and Practices[15]
FacadeProvide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.YesYesN/A
FlyweightUse sharing to support large numbers of similar objects efficiently.YesNoN/A
Front controllerThe pattern relates to the design of Web applications. It provides a centralized entry point for handling requests.NoNo

J2EE Patterns[16]PoEAA[17]

MarkerEmpty interface to associate metadata with a class.NoNoEffective Java[18]
ModuleGroup several related elements, such as classes, singletons, methods, globally used, into a single conceptual entity.NoNoN/A
ProxyProvide a surrogate or placeholder for another object to control access to it.YesNoN/A
Twin[19]Twin allows modeling of multiple inheritance in programming languages that do not support this feature.NoNoN/A

Behavioral patterns[edit]

Software Design Patterns Tutorial C++

NameDescriptionIn Design PatternsIn Code Complete[13]Other
BlackboardArtificial intelligence pattern for combining disparate sources of data (see blackboard system)NoNoN/A
Chain of responsibilityAvoid 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.YesNoN/A
CommandEncapsulate 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.YesNoN/A
InterpreterGiven a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.YesNoN/A
IteratorProvide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.YesYesN/A
MediatorDefine 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.YesNoN/A
MementoWithout violating encapsulation, capture and externalize an object's internal state allowing the object to be restored to this state later.YesNoN/A
Null objectAvoid null references by providing a default object.NoNoN/A
Observer or Publish/subscribeDefine a one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically.YesYesN/A
ServantDefine 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.NoNoN/A
SpecificationRecombinable business logic in a Boolean fashion.NoNoN/A
StateAllow an object to alter its behavior when its internal state changes. The object will appear to change its class.YesNoN/A
StrategyDefine a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.YesYesN/A
Template methodDefine 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.YesYesN/A
VisitorRepresent 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.YesNoN/A

Concurrency patterns[edit]

NameDescriptionIn POSA2[20]Other
Active ObjectDecouples 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.YesN/A
BalkingOnly execute an action on an object when the object is in a particular state.NoN/A
Binding propertiesCombining multiple observers to force properties in different objects to be synchronized or coordinated in some way.[21]NoN/A
Compute kernelThe 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.NoN/A
Double-checked lockingReduce 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.

YesN/A
Event-based asynchronousAddresses problems with the asynchronous pattern that occur in multithreaded programs.[22]NoN/A
Guarded suspensionManages operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed.NoN/A
JoinJoin-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.NoN/A
LockOne thread puts a 'lock' on a resource, preventing other threads from accessing or modifying it.[23]NoPoEAA[14]
Messaging design pattern (MDP)Allows the interchange of information (i.e. messages) between components and applications.NoN/A
Monitor objectAn object whose methods are subject to mutual exclusion, thus preventing multiple objects from erroneously trying to use it at the same time.YesN/A
ReactorA reactor object provides an asynchronous interface to resources that must be handled synchronously.YesN/A
Read-write lockAllows concurrent read access to an object, but requires exclusive access for write operations.NoN/A
SchedulerExplicitly control when threads may execute single-threaded code.NoN/A
Thread poolA 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.NoN/A
Thread-specific storageStatic or 'global' memory local to a thread.YesN/A

Documentation[edit]

The documentation for a design pattern describes the context in which the pattern is used, the forces within the context that the pattern seeks to resolve, and the suggested solution.[24] There is no single, standard format for documenting design patterns. Rather, a variety of different formats have been used by different pattern authors. However, according to Martin Fowler, certain pattern forms have become more well-known than others, and consequently become common starting points for new pattern-writing efforts.[25] One example of a commonly used documentation format is the one used by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides in their book Design Patterns. It contains the following sections:

  • Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern.
  • Intent: A description of the goal behind the pattern and the reason for using it.
  • Also Known As: Other names for the pattern.
  • Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used.
  • Applicability: Situations in which this pattern is usable; the context for the pattern.
  • Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose.
  • Participants: A listing of the classes and objects used in the pattern and their roles in the design.
  • Collaboration: A description of how classes and objects used in the pattern interact with each other.
  • Consequences: A description of the results, side effects, and trade offs caused by using the pattern.
  • Implementation: A description of an implementation of the pattern; the solution part of the pattern.
  • Sample Code: An illustration of how the pattern can be used in a programming language.
  • Known Uses: Examples of real usages of the pattern.
  • Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.

Criticism[edit]

It has been observed that design patterns may just be a sign that some features are missing in a given programming language (Java or C++ for instance). Peter Norvig demonstrates that 16 out of the 23 patterns in the Design Patterns book (which is primarily focused on C++) are simplified or eliminated (via direct language support) in Lisp or Dylan.[26] Related observations were made by Hannemann and Kiczales who implemented several of the 23 design patterns using an aspect-oriented programming language (AspectJ) and showed that code-level dependencies were removed from the implementations of 17 of the 23 design patterns and that aspect-oriented programming could simplify the implementations of design patterns.[27] See also Paul Graham's essay 'Revenge of the Nerds'.[28]

Inappropriate use of patterns may unnecessarily increase complexity.[29]

See also[edit]

References[edit]

  1. ^Smith, Reid (October 1987). Panel on design methodology. OOPSLA '87 Addendum to the Proceedings. doi:10.1145/62138.62151. Ward cautioned against requiring too much programming at, what he termed, 'the high level of wizards.' He pointed out that a written 'pattern language' can significantly improve the selection and application of abstractions. He proposed a 'radical shift in the burden of design and implementation' basing the new methodology on an adaptation of Christopher Alexander's work in pattern languages and that programming-oriented pattern languages developed at Tektronix has significantly aided their software development efforts.
  2. ^Beck, Kent; Cunningham, Ward (September 1987). Using Pattern Languages for Object-Oriented Program. OOPSLA '87 workshop on Specification and Design for Object-Oriented Programming. Retrieved 2006-05-26.
  3. ^Baroni, Aline Lúcia; Guéhéneuc, Yann-Gaël; Albin-Amiot, Hervé (June 2003). 'Design Patterns Formalization'. Nantes: École Nationale Supérieure des Techniques Industrielles et des Mines de Nantes. CiteSeerX10.1.1.62.6466.Cite journal requires journal= (help)
  4. ^Bishop, Judith. 'C# 3.0 Design Patterns: Use the Power of C# 3.0 to Solve Real-World Problems'. C# Books from O'Reilly Media. Retrieved 2012-05-15. If you want to speed up the development of your .NET applications, you're ready for C# design patterns -- elegant, accepted and proven ways to tackle common programming problems.
  5. ^Meyer, Bertrand; Arnout, Karine (July 2006). 'Componentization: The Visitor Example'(PDF). IEEE Computer. 39 (7): 23–30. CiteSeerX10.1.1.62.6082. doi:10.1109/MC.2006.227.
  6. ^Laakso, Sari A. (2003-09-16). 'Collection of User Interface Design Patterns'. University of Helsinki, Dept. of Computer Science. Retrieved 2008-01-31.
  7. ^Heer, J.; Agrawala, M. (2006). 'Software Design Patterns for Information Visualization'. IEEE Transactions on Visualization and Computer Graphics. 12 (5): 853–60. CiteSeerX10.1.1.121.4534. doi:10.1109/TVCG.2006.178. PMID17080809.
  8. ^Dougherty, Chad; Sayre, Kirk; Seacord, Robert C.; Svoboda, David; Togashi, Kazuya (2009). Secure Design Patterns(PDF). Software Engineering Institute.
  9. ^Garfinkel, Simson L. (2005). Design Principles and Patterns for Computer Systems That Are Simultaneously Secure and Usable (Ph.D. thesis).
  10. ^'Yahoo! Design Pattern Library'. Archived from the original on 2008-02-29. Retrieved 2008-01-31.
  11. ^'How to design your Business Model as a Lean Startup?'. 2010-01-06. Retrieved 2010-01-06.
  12. ^Pattern Languages of Programming, Conference proceedings (annual, 1994—) [1]
  13. ^ abcMcConnell, Steve (June 2004). 'Design in Construction'. Code Complete (2nd ed.). Microsoft Press. p. 104. ISBN978-0-7356-1967-8. Table 5.1 Popular Design Patterns
  14. ^ abFowler, Martin (2002). Patterns of Enterprise Application Architecture. Addison-Wesley. ISBN978-0-321-12742-6.
  15. ^C. Martin, Robert (2002). '28. Extension object'. Agile Software Development, Principles, Patterns, and Practices. p. 408. ISBN978-0135974445.
  16. ^Alur, Deepak; Crupi, John; Malks, Dan (2003). Core J2EE Patterns: Best Practices and Design Strategies. Prentice Hall. p. 166. ISBN978-0-13-142246-9.
  17. ^Fowler, Martin (2002). Patterns of Enterprise Application Architecture. Addison-Wesley. p. 344. ISBN978-0-321-12742-6.
  18. ^Bloch, Joshua (2008). 'Item 37: Use marker interfaces to define types'. Effective Java (Second edition). Addison-Wesley. p. 179. ISBN978-0-321-35668-0.
  19. ^'Twin – A Design Pattern for Modeling Multiple Inheritance'(PDF).
  20. ^Schmidt, Douglas C.; Stal, Michael; Rohnert, Hans; Buschmann, Frank (2000). Pattern-Oriented Software Architecture, Volume 2: Patterns for Concurrent and Networked Objects. John Wiley & Sons. ISBN978-0-471-60695-6.
  21. ^Binding Properties
  22. ^Nagel, Christian; Evjen, Bill; Glynn, Jay; Watson, Karli; Skinner, Morgan (2008). 'Event-based Asynchronous Pattern'. Professional C# 2008. Wiley. pp. 570–571. ISBN978-0-470-19137-8.
  23. ^Lock Pattern
  24. ^Gabriel, Dick. 'A Pattern Definition'. Archived from the original on 2007-02-09. Retrieved 2007-03-06.
  25. ^Fowler, Martin (2006-08-01). 'Writing Software Patterns'. Retrieved 2007-03-06.
  26. ^Norvig, Peter (1998). Design Patterns in Dynamic Languages.
  27. ^Hannemann, Jan (2002). Design pattern implementation in Java and AspectJ.
  28. ^Graham, Paul (2002). Revenge of the Nerds. Retrieved 2012-08-11.
  29. ^McConnell, Steve (2004). Code Complete: A Practical Handbook of Software Construction, 2nd Edition. p. 105.

Further reading[edit]

  • Alexander, Christopher; Ishikawa, Sara; Silverstein, Murray; Jacobson, Max; Fiksdahl-King, Ingrid; Angel, Shlomo (1977). A Pattern Language: Towns, Buildings, Construction. New York: Oxford University Press. ISBN978-0-19-501919-3.
  • Alur, Deepak; Crupi, John; Malks, Dan (May 2003). Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition). Prentice Hall. ISBN978-0-13-142246-9.
  • Beck, Kent (October 2007). Implementation Patterns. Addison-Wesley. ISBN978-0-321-41309-3.
  • Beck, Kent; Crocker, R.; Meszaros, G.; Coplien, J. O.; Dominick, L.; Paulisch, F.; Vlissides, J. (March 1996). Proceedings of the 18th International Conference on Software Engineering. pp. 25–30.
  • Borchers, Jan (2001). A Pattern Approach to Interaction Design. John Wiley & Sons. ISBN978-0-471-49828-5.
  • Coplien, James O.; Schmidt, Douglas C. (1995). Pattern Languages of Program Design. Addison-Wesley. ISBN978-0-201-60734-5.
  • Coplien, James O.; Vlissides, John M.; Kerth, Norman L. (1996). Pattern Languages of Program Design 2. Addison-Wesley. ISBN978-0-201-89527-8.
  • Eloranta, Veli-Pekka; Koskinen, Johannes; Leppänen, Marko; Reijonen, Ville (2014). Designing Distributed Control Systems: A Pattern Language Approach. Wiley. ISBN978-1118694152.
  • Fowler, Martin (1997). Analysis Patterns: Reusable Object Models. Addison-Wesley. ISBN978-0-201-89542-1.
  • Fowler, Martin (2003). Patterns of Enterprise Application Architecture. Addison-Wesley. ISBN978-0-321-12742-6.
  • Freeman, Eric; Freeman, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Head First Design Patterns. O'Reilly Media. ISBN978-0-596-00712-6.
  • Hohmann, Luke; Fowler, Martin; Kawasaki, Guy (2003). Beyond Software Architecture. Addison-Wesley. ISBN978-0-201-77594-5.
  • Gabriel, Richard (1996). Patterns of Software: Tales From The Software Community(PDF). Oxford University Press. p. 235. ISBN978-0-19-512123-0. Archived from the original(PDF) on 2003-08-01.
  • Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN978-0-201-63361-0.
  • Hohpe, Gregor; Woolf, Bobby (2003). Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions. Addison-Wesley. ISBN978-0-321-20068-6.
  • Holub, Allen (2004). Holub on Patterns. Apress. ISBN978-1-59059-388-2.
  • Kircher, Michael; Völter, Markus; Zdun, Uwe (2005). Remoting Patterns: Foundations of Enterprise, Internet and Realtime Distributed Object Middleware. John Wiley & Sons. ISBN978-0-470-85662-8.
  • Larman, Craig (2005). Applying UML and Patterns. Prentice Hall. ISBN978-0-13-148906-6.
  • Liskov, Barbara; Guttag, John (2000). Program Development in Java: Abstraction, Specification, and Object-Oriented Design. Addison-Wesley. ISBN978-0-201-65768-5.
  • Manolescu, Dragos; Voelter, Markus; Noble, James (2006). Pattern Languages of Program Design 5. Addison-Wesley. ISBN978-0-321-32194-7.
  • Marinescu, Floyd (2002). EJB Design Patterns: Advanced Patterns, Processes and Idioms. John Wiley & Sons. ISBN978-0-471-20831-0.
  • Martin, Robert Cecil; Riehle, Dirk; Buschmann, Frank (1997). Pattern Languages of Program Design 3. Addison-Wesley. ISBN978-0-201-31011-5.
  • Mattson, Timothy G; Sanders, Beverly A.; Massingill, Berna L. (2005). Patterns for Parallel Programming. Addison-Wesley. ISBN978-0-321-22811-6.
  • Shalloway, Alan; Trott, James R. (2001). Design Patterns Explained, Second Edition: A New Perspective on Object-Oriented Design. Addison-Wesley. ISBN978-0-321-24714-8.
  • Vlissides, John M. (1998). Pattern Hatching: Design Patterns Applied. Addison-Wesley. ISBN978-0-201-43293-0.
  • Weir, Charles; Noble, James (2000). Small Memory Software: Patterns for systems with limited memory. Addison-Wesley. ISBN978-0-201-59607-6. Archived from the original on 2007-06-17.

Software Design Patterns Ppt

Retrieved from 'https://en.wikipedia.org/w/index.php?title=Software_design_pattern&oldid=917694694'