© James E. McDonough 2017

James E. McDonough, Object-Oriented Design with ABAP, 10.1007/978-1-4842-2838-8_10

10. Design Patterns

James E. McDonough

(1)Pennington, New Jersey, USA

Now that we know the basic principles of object-oriented design and have become familiar with the class diagrams offered by the Unified Modeling Language, we are now ready to begin our exploration of the galaxy known as Design Patterns.

Those of us who write code for living occasionally experience a sense of déjà vu – that we have already written something identical or similar once before in some other program, but can’t remember exactly where or when. Some of us may remember where and when we did something similar; and some of us may even have a collection of code snippets (or entire programs) from which we can copy and paste sections of code and tailor them to the specific task at hand. Whether we recognize a programming challenge as one for which we have a handy snippet of code available or simply one for which we have a sense of déjà vu, the common denominator between the two is that we recognize a pattern that we have seen before. These patterns with which we are familiar and for which we might have a handy snippet of code available to use as a model enable us to reuse a proven solution in the new design on which we are working. These constitute our personal collection of design patterns.

These design patterns are not the same as callable utilities that can produce some desired result. For instance, I often find myself writing classes to hold a cache of records read from a persistent data storage device, the idea being that if I need the same record more than once during processing I can obtain it faster from the cache than by reading it again from the slower persistent data storage device. Accordingly, these caching classes are customized for a specific type of persistent storage record and for a specific set of columns from that type of record. It is not practical to write a single callable utility that can handle any set of columns from many different types of records. So I find myself devising multiple small classes to handle the specifics I need, but all of them use the same basic design pattern for retaining a subset of columns of records read from the persistent data storage device. The design pattern lays out the type of solution to build, and writing a new caching class is the manifestation of that design pattern applied to a specific use.

Other programmers we encounter during our careers will also have their personal collection of design patterns they use to solve their design challenges. Some design patterns are so pervasive in data processing that many different programmers have recognized the same patterns and have exchanged ideas with each other on the best ways to implement solutions using the pattern. Indeed, there are those in the data processing industry who believe virtually every programming challenge has already been encountered and solved by someone else.

The Gang of Four

In 1995, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides compiled a set of 23 such common design patterns into their now-famous book Design Patterns: Elements of Reusable Object-Oriented Software. 1 It was the first generally available catalog of design patterns applicable to computer programming. They did for data processing what Christopher Alexander and his colleagues did nearly 20 years earlier for architecture.2 The book had a significant impact on the software development industry and, more than 20 years later, remains the definitive compendium of design patterns for use in computer programming. It not only describes 23 of the most commonly recurring patterns, but defines a language for speaking about design patterns. The four authors have collectively become known as the “Gang of Four,” and many software designers now refer to the book simply by the acronym for this moniker: GoF.

GoF defines a template for describing a design pattern, and all the design patterns it contains are all described using this same template. The template includes, among others, the name of the pattern, a short statement describing the pattern, advice on where the pattern is applicable, example code, and related patterns. The example code primarily uses C++ and Smalltalk, which can present a challenge to those who are unfamiliar with these languages. However, the catalog is so thorough that it has been embraced by software designers specializing in many other object-oriented languages.

GoF classifies its 23 design patterns using two criteria: purpose and scope.

  • Purpose reflects what the pattern does, and is subdivided into three categories: creational, structural, and behavioral.

    “Creational patterns concern the process of object creation. Structural patterns deal with the composition of classes or objects. Behavioral patterns characterize the ways in which classes or objects interact and distribute responsibility.”3

  • Scope has two categories: class and object.

    “Scope specifies whether the pattern applies primarily to classes or to objects. Class patterns deal with relationships between classes and their subclasses. These relationships are established through inheritance, so they are static – fixed at compile-time. Object patterns deal with object relationships, which can be changed at runtime and are more dynamic. Almost all patterns use inheritance to some extent. So the only patterns labeled ‘class patterns’ are those that focus on class relationships.”4

The combinations of the two criteria provide a convenient way to perceive patterns.

  • Creational class patterns defer some part of object creation to subclasses, while creational object patterns defer it to another object.”

  • “The Structural class patterns use inheritance to compose classes, while the Structural object patterns describe ways to assemble objects.”

  • “The Behavioral class patterns use inheritance to describe algorithms and flow of control, whereas the Behavioral object patterns describe how a group of objects cooperate to perform a task that no single object can carry out alone.”5

Table 10-1 represents the organization of the 23 GoF design patterns.6

Table 10-1. Organization of the 23 GoF Design Patterns
 

Purpose

Creational

Structural

Behavioral

Scope

Class

Factory Method

Adapter (class)

Interpreter

Template Method

Object

Abstract Factory

Builder

Prototype

Singleton

Adapter (object)

Bridge

Composite

Decorator

Façade

Flyweight

Proxy

Chain of Responsibility

Command

Iterator

Mediator

Memento

Observer

State

Strategy

Visitor

Notice that Adapter is the only one of the GoF patterns that has both a class scope as well as an object scope.7

The GoF book establishes the outline used to describe each design pattern:8

  1. Pattern name and classification: The classification represents the purpose and scope as shown in Table 10-1.

  2. Intent: Essentially a sentence or two describing the pattern.

  3. Also Known As: Other names, if any, by which the pattern is known.

  4. Motivation: A scenario describing a design challenge suited for the pattern.

  5. Applicability: Advisory on situations when the pattern is appropriate as well as inappropriate.

  6. Structure: A diagram of the design pattern showing the interaction of the participants.

  7. Participants: The types of individual classes and interfaces used in the pattern.

  8. Collaborations: The interaction between the participants.

  9. Consequences: Both positive and negative aspects of using the pattern.

  10. Implementation: Details about how the pattern is to be implemented.

  11. Sample Code: GoF uses C++ and Smalltalk.

  12. Known Uses: Examples of real software packages using the pattern.

  13. Related Patterns: Other design patterns exhibiting similarities, highlighting the significant differences between them, and other patterns that are particularly suitable in multi-pattern collaborative designs.

The Design Pattern Name

In my Object-Oriented Chalk Talks, I usually start the section on design patterns by telling the class that I am going to play the role of a business analyst, and share with them all the information about a new application I want them to implement in ABAP. I use the white board to list various capabilities I want included as I speak about the new application, which is to show those rows from a specific persistence repository database which are missing values for certain columns:

  • “This application is to produce a report that needs to allow the user to scroll forward and backward through the list of applicable rows, as well as scroll left and right when the columns all cannot fit on the screen at the same time. The user needs to be able to print the report as well as save the results to a local file. The user needs to be able to get totals for numeric columns as well as have the ability to produce control breaks for selected columns. It would be nice if the report also provided the user with the capability to select a row, push a button, and see the values for all of the columns of that row shown in a pop-up box. It also would be helpful to the user if they were able to rearrange the order of the columns at will, change the width of a column by dragging a column boundary, left to shorten and right to lengthen, as well as hide selected columns from the report, which can be unhidden later. Another feature the users require is the ability to sort the rows by a specific column value as well as filter out those rows which do or do not conform to some criteria value or range the user could specify for the column. Also, a find feature is necessary to locate rows in the report which contain some specified value or partial value. It would be great if we could present the report such that it enables users to manipulate the content similar to the way a spreadsheet works. In addition, it would be nice if users were able to save the display settings of the report after they had applied sorting and filtering criteria, so they could recall that format with each new use. It would be nicer still if these saved display settings could be presented in a list, enabling the user to select the display settings they need at that moment. … ”

I continue this narrative for a while until someone eventually interrupts me.

“Jim,” they say, “why don’t you simply tell us to use ALV,9 which already provides all of those capabilities?”

“Yes,” I tell them, “that is exactly the point for having a good name for a design pattern .” A name enables us simply to state the name of the design pattern during design discussions and everyone immediately knows all the implications associated with that name. It is similar to the proverbial cliché about a picture being worth a thousand words. Refer back to the long business analyst narrative above where I used over 300 words to describe a process which could be described very succinctly by this two-word statement:

  • Use ALV.

Patterns exist in other fields of endeavor besides architecture and software design , with each field having its own named patterns to be used to facilitate discussions between people who both are familiar with the field of endeavor and know the relevant pattern names. The Karo-Cann Defense immediately connotes a king pawn opening while the Albin Counter Gambit indicates a queen pawn opening,10 but each name alleviates the need for further explanation about the opening sequence of moves in chess matches where these patterns are used. The names derecho, tornado, and hurricane describe severe weather patterns, each of which carries its own implications about wind speeds and precipitation that require no elaboration. Similarly, the alternate merge pattern is familiar to drivers who find themselves in the situation where two lanes of traffic are converging into a single lane, while the holding stack pattern is familiar to commercial airline pilots waiting to land at heavy-traffic airports. Fibonacci, prime number, and Mandelbrot set describe number patterns, while textile patterns include argyle, glen plaid, and houndstooth. Flemish, monk, and sussex are variations of load-bearing bond brickwork patterns, whereas basket weave, herringbone, and della robia are variations of non-load-bearing bond brickwork patterns. In each case, simply using the name of the pattern instantly conveys a wealth of information that might otherwise require many paragraphs of explanation and much time expended.

Patterns Explored in this Book

The following list of names covers the patterns we will be exploring over the next few chapters:

  1. Singleton

  2. Strategy

  3. Observer

  4. Factory

  5. Adapter

  6. Decorator

  7. Chain of Responsibility

  8. Iterator

  9. Template Method

  10. Command

  11. Null Object

  12. State

  13. Lazy Initialization

  14. Flyweight

  15. Memento

  16. Visitor

Of these, Null Object (11) and Lazy Initialization (13) are not included in the GoF book.

Use of UML Class Diagrams to Illustrate Design Patterns

The GoF book was published a year before UML was invented. Accordingly, although GoF provides a class diagram for each design pattern, these diagrams do not use the UML notation. Instead, each one is illustrated using James Rumbaugh’s Object Modeling Technique (OMT). The UML class diagrams accompanying the design patterns covered over the next few chapters approximate the OMT structure diagrams included in GoF.

Also, because design patterns are general solutions to recurring design challenges, the class diagrams themselves are somewhat generalized to accommodate variations on different ways in which the design patterns can be manifested. Amongst others, the following liberties were taken with the UML class diagrams:

  • The relationship lines representing aggregation (“has a;” ) and composition (“owns a;”) differ from each other in their designation for whether or not the referenced object is destroyed when the referring object is destroyed. The UML diagrams in the following chapters do not distinguish between them, and are illustrated using only the aggregation relationship line.

    A447555_1_En_10_Figa_HTML.jpg
    A447555_1_En_10_Figb_HTML.jpg
  • Aggregation relationship lines are usually accompanied by multiplicity indications on both ends of the lines. To allow for more general combinations, these numbers have been omitted in some cases.

  • The designation by GoF that a participant is or provides an interface is interpreted in the broadest sense, and is not taken to mean that the participant is defined specifically as a stand-alone interface, for which the UML notation normally would include a <<interface>> banner along with the entity name in the name box. Instead, the interpretation of the word interface is in the context of the public interface provided by the entity, which could be furnished using either a class or an interface component. Therefore, unless otherwise required for clarity, classes are not shown implementing an interface, but instead are shown inheriting from a superclass. When it contributes only abstract methods, the superclass entity should be regarded as a general place holder for either a class or a stand-alone interface, and its connecting generalization relationship lines used to denote inheritance should be regarded as proxies for the connecting realization relationship lines used to denote the implementation of stand-alone interfaces.

Summary

In this chapter, we learned that there are names for those general algorithms we find ourselves using over and over again in different situations: design patterns. We also learned that other programmers also have their own collection of such patterns, and that in 1995 the Gang of Four compiled the first published catalog of 23 design patterns applicable to computer programming. We now understand the importance of having a good name for a design pattern since it simplifies communications we have with our colleagues about software designs.

Footnotes

1 Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1995.

2 Refer to A Pattern Language: Towns, Buildings, Construction by Christoper Alexander, Sara Ishikawa, Murray Silverstein, Max Jacobson, Ingrid Fiksdahl-King, ShlomoAngel; Oxford University Press, 1977.

3 GoF, p. 10

4 GoF , p. 10

5 GoF, p. 10

6 From Table 1.1: Design pattern space, GoF, p. 10

7 One pattern not included amongst the 23 GoF design patterns is known as the Model-View-Controller pattern (a.k.a. MVC), the name of which may already be familiar to many ABAP programmers due to its repeated mention in the book ABAP Objects: ABAP Programming in SAP NetWeaver (Horst Keller, Sascha Krűger; 2nd edition, Galileo Press, 2007), in addition to the plethora of articles available via the Internet on the topic of MVC with ABAP. Indeed, the GoF book describes MVC (pp. 4-6) as a compound design pattern consisting of an Observer, a Composite, and a Strategy pattern all working in cooperation with each other.

8 GoF, p. 6.

9 ALV is the acronym for the SAP Application List Viewer, and has become the definitive technique for producing reports in ABAP programs.

10 Fred Reinfeld, The Complete Chess Course, Doubleday, 1953.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset