GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing thinkinginpython.com — Design Patterns · Thinking in Python
Index
Chapter 21
Design Patterns
The “design patterns” movement was an important step forward in object-oriented design. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides carried it into the mainstream with their 1994 book Design Patterns. The four became known as the “Gang of Four”1. I refer to that book as GoF Design Patterns, and use design patterns for the concept. GoF Design Patterns shows 23 solutions to particular classes of problems, along with one or more examples for each, typically in C++ but sometimes in Smalltalk. Many of those examples inspired the ones in this part of the book. This chapter introduces the concepts. Its one listing shows a pattern shrinking to a function. The chapters that follow supply the rest of the code. What Is a Pattern?At first, think of a pattern as an especially clever and insightful way to solve a particular class of problems. Many people have worked out all the angles of a problem and arrived at the most general, flexible solution. You may have seen and solved something like it before, but your solution probably lacks the completeness a pattern embodies. That completeness has a failure mode. When you know a catalog of patterns, that catalog tempts you to treat it as a checklist, and to install patterns as proof of sophistication. A pattern belongs in your program only when you have the problem it solves. Machinery for isolating variation needs a variation to isolate. Despite the name “design patterns,” patterns apply beyond design. Because a pattern translates into code, you might expect it to appear first in low-level design. But a pattern embodies a complete idea within a program, so it can appear at the analysis phase or high-level design phase, where you are still describing what the system does rather than how to build it. A pattern appears at every level. Often you first discover that you need one when you reach the code. The basic concept of a pattern is also the basic concept of program design: adding a layer of abstraction. Whenever you abstract something, you isolate particular details. One of the most compelling motivations for abstraction is to separate things that change from things that stay the same. Once you find a part of your program that’s likely to change, patterns can keep those changes from reaching the rest of your code. That isolation confines each change to one place, which makes the code easier to maintain and usually simpler to understand. What an Abstraction ErasesIsolating what changes discards information. An abstraction is a guess about which details no caller will need. A good abstraction does more than hide those details. It erases them. Code outside the boundary cannot recover information the boundary discards, so a caller that turns out to need an erased detail cannot work around the interface. Someone must change the interface. The art of design lies in guessing well about which details you can hide and which you must expose. Erased details are also the source of scaling limits. Every abstraction hides some work that takes negligible time at the size you built it: a copy, a sort, a lookup behind an attribute. A growing system eventually reaches the size where one piece of hidden work dominates the running time. The layer that made the code simple now hides the work you need to change. That hidden work is one reason Performance tells you to measure at a realistic size rather than trust a small trial. The Vector of ChangeOften, the most difficult part of developing an elegant and easy-to-maintain design is discovering what I call “the vector of change” (here, “vector” means a direction of change, not an array of numbers). You look for the most important thing that changes, because most of your maintenance effort goes into that change. Once you discover the vector of change, you have the focal point around which to structure your design. You discover a vector of change. You do not predict it. Guessing at it up front often adds complexity to allow flexibility in a direction that goes unused. The second time a requirement changes the same part of the design, you have evidence. Patterns You Have Already SeenYou have seen some design patterns in this book. For example, you can think of inheritance as a design pattern (albeit one built into the language). Inheritance lets you express differences in behavior in objects that all have the same interface. The behavior changes from one subclass to the next, while the interface stays the same. Composition also qualifies as a pattern, since it lets you change the objects to which your class delegates, and with them the way that class works. You can make that change dynamically or statically. Another pattern that appears in GoF Design Patterns is the Iterator. An iterator lets you hide the particular implementation of the container as you step through it. You can write generic code that operates on all the elements in a sequence, whether the sequence holds them in an array, a linked list, or a tree. The code works with any object that produces an iterator. Pattern EvolutionA pattern develops in stages, each more general than the last:
In Python terms: The stages are a history, not a ranking. Patterns are subtle and appear over time, so leave a solution at the stage it has reached rather than forcing it toward a design pattern. The progression also runs in reverse. A pattern that a language builds in becomes an idiom again, stage one. Programmers who arrive next learn it as syntax rather than as a design. Stepping through a container is stage one in Python and was stage four in the GoF Design Patterns examples. When a Pattern DissolvesA pattern is often a sign of something missing in a language. Programmers wrote the same supporting code often enough that it acquired a name. The pattern exists because the language leaves that code for them to write. A language can supply that missing
piece in two ways. Sometimes a language adds the feature, and
the feature replaces the pattern2. Iterator
is the clear case. It was implicit in the Here is the whole of a Strategy in Python: The classic form declares a
This listing shows only the shape. A function with a Pattern TaxonomyGoF Design Patterns discusses 23 patterns and sorts them under three purposes, each named for what its patterns do:
The catalog above comes from GoF. Patterns from outside it, like the Null Object and the Data Transfer Object, appear in the Pattern Catalog. I’ve found the GoF Design Patterns classification too obscure, and not always helpful. Certainly, the Creational patterns are straightforward. How will you create objects? This is a normal question, and the name tells you which group of patterns answers it. But I find Structural and Behavioral far less useful distinctions. I have not been able to look at a problem and say “clearly, you need a structural pattern here,” so that classification doesn’t lead me to a solution (I’ll readily admit that I may be missing something here). Patterns often resemble each other more in their implementations than the GoF Design Patterns categories suggest. This book groups them by that resemblance. Surrogate treats Proxy and State as one front-object structure. Function Objects treats Command, Strategy, and Chain of Responsibility as one function-passing structure. Composite and Interpreter treats both of its patterns as one recursive-data structure. When two patterns share a structure, learning one teaches you most of the other. The remaining difference is intent. CouplingEvery pattern in GoF Design Patterns answers one question: what does one part of a program know about another? GoF’s first chapter lists eight “common causes of redesign” and names the patterns that address each one. Six of the eight are a dependence of one part on another: on a class name, on a specific operation, on a platform, on an object’s representation, on an algorithm, or on each other, which the list calls tight coupling. The other two are about what a dependence makes hard once it exists: extending by subclassing, and altering a class. The glossary defines coupling as “the degree to which software components depend on each other.” Both of that first chapter’s design principles tell you to loosen one particular dependence. “Program to an interface, not an implementation” says stop specifying concrete classes. “Favor object composition over class inheritance” says stop inheriting implementations. GoF Design Patterns has a name for the result, abstract coupling. A class that holds a reference to an abstract class “refers to a type of object, not a concrete object.” Read this way, the catalog is one idea applied twenty-three times. GoF’s own discussion of the behavioral patterns compares four of them by their coupling. Command, Observer, Mediator, and Chain of Responsibility each decouple a sender from a receiver, “but with different trade-offs.” Observer “defines a looser sender-receiver binding than Command.” A diagram makes coupling visible. Once you can see coupling, the patterns in the chapters ahead stop being twenty-three shapes to memorize, and become a few moves applied to one kind of diagram. What One Part Knows About AnotherCoupling has degrees. Every working program has parts that depend on each other, so the question is how much of the other part a dependence reaches. Each rung is something the
dependent part knows. A subclass knows its parent’s internals:
which methods call which, the attributes’ names, what a
The rung a dependence sits on decides how many parts a change
can reach. If you rename a method on a class that other code
subclasses, every subclass that overrides or calls the old name
must change. If you rename it on a class that other code reaches
through a In Python, an implementer meets the The A Pattern Moves an EdgeIn a design drawn as parts and the edges between them, each edge says what the dependent part knows. A heavy edge names a concrete class. A thin edge names an interface. A dashed edge with a hollow head says the part satisfies that interface. With those three edges alone, six GoF patterns look like this: The red box in each panel marks the part the pattern protects from change. Read the heavy edges first, because a change to the class at the head of a heavy edge can force an edit in the part at its tail. Strategy has none. The context specifies an interface and each algorithm satisfies it, so adding an algorithm leaves every existing part as it was. Observer has one, and it
points from the observer to the subject. An observer specifies
its subject’s class in Factory Method keeps a heavy edge too. Something must specify a class to construct it. The pattern moves that choice out of the client and into a creator. Naming the concrete product is the creator’s whole job. The client knows the creator and the product through their interfaces. Adapter moves the heavy edge inside the adapter. The client specifies the target interface. The adapter alone knows the adaptee’s real name, so a change to the adaptee reaches one file. Decorator, like Strategy, points every edge at its interface. A topping satisfies the component interface and also holds a component, so it can wrap a pizza or another topping, knowing each one through that interface. Visitor is the reverse of the others. The visitor specifies every concrete element. The pattern concentrates the heavy edges in the visitors on purpose. Adding an operation means writing one new visitor and leaving every other part as it was, while adding an element type means changing every visitor. That choice defines Visitor. The diagram shows where the choice puts the heavy edges. Seen this way, the patterns differ less in how much coupling they carry than in where they put it and which way it points. A heavy edge is acceptable when it sits in a part that is easy to change, or points at a part that rarely changes. The Managed Coupling principle asks for this: coupling you can see and have placed on purpose. The Reach of a ChangeCoupling decides which existing
parts you edit when you add a part. A The dashed box is the new class. The shaded parts are the
existing ones whose source changes when you add
On the left, A change to a part can force an edit in every part with a heavy edge pointing at it. A pattern moves those edges, usually out of the parts that change often and into one part you can find. The Edge Python DeletesOne more diagram explains why so many of the pattern chapters
subtract code as they go. Take a caller, a function
With an abstract base class, two
edges exist in source: the caller specifies The edge a One question serves for every pattern chapter. Which edge does this pattern move, and where does it put it? Design PrinciplesDesign principles are at least as important as design patterns, but they do a different job. A pattern is a shape of solution. A principle is a test you apply to the shape you chose: a claim the design either satisfies or violates. Most of the principles below hold for any code, but Reflexivity and the Law of Demeter assume classes and objects. The list is a reference. Later chapters name a few of these principles when a design depends on them. The rest are here for your own designs.
Reading the Chapters AheadMost of the chapters ahead take a pattern, or a family of patterns that share a structure, and ask three questions of it. What changes and what stays the same? That describes the problem the pattern exists to solve. How much of the answer does Python supply on its own? That decides how much remains for you to write. What remains after you subtract Python’s share? That remainder is the part to learn, and it is usually the intent rather than the structure. A pattern that subtracts to nothing is not a mistake. It is the right answer for a language missing the piece Python has. From Iterator through Memento, each pattern chapter includes a figure of its pattern at work, drawn from that chapter’s own listings. Data Transfer Objects is the one chapter in that range without a figure. The gallery in A Pattern Moves an Edge shows which way each edge points, while each chapter’s figure shows what happens, in what order, and which part knows about which. Part III closes with a Pattern Catalog, a name-and-intent index of the wider literature, with a link to this book’s coverage wherever it exists. ExercisesTry each exercise before opening its solution.
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |