SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
Copyright ©2007, Google Inc
Design Patterns in Python
Alex Martelli (aleax@google.com)
http://www.aleax.it/gdd_pydp.pdf
The "levels" of this talk
2
Shu
Ha
Ri
Py
DP("Retain")
("Detach")
("Transcend")
Hit the ground running...
3
"Forces": some rich,
complex subsystem
offers a lot of useful
functionality; client
code interacts with
several parts of this
functionality in a way
that's "out of control"
this causes many
problems for client-code
programmers AND
subsystem ones too (complexity + rigidity)
Solution: the "Facade" DP
4
interpose a simpler
"Facade" object/class
exposing a controlled
subset of functionality
client code now calls
into the Facade, only
the Facade implements
its simpler functionality
via calls into the rich,
complex subsystem
subsystem implementation
gains flexibility, clients gain simplicity© 2004 AB Strakt 17
DP "Facade"
! existing supplier code ! provides ric
complex functionality in protocol S
! we need a simpler "subset" C of S
! facade code " implements and supp
(by calling S on !)
Facade is a Design Pattern
summary of a frequent design problem +
structure of a solution to that problem (+
pros and cons, alternatives, ...), and:
A NAME (much easier to retain/discuss!)
"descriptions of communicating objects and
classes customized to solve a general design
problem in a particular context"
that's NOT: a data structure, algorithm,
domain-specific system architecture,
programming-language/library feature
MUST be studied in a language's context!
MUST supply Known Uses ("KU")
5
Some Facade KUs
...in the Python standard library...:
dbhash facades for bsddb
highly simplified/subset access
also meets the "dbm" interface (thus,
also an example of the Adapter DP)
os.path: basename, dirname facade for
split + indexing; isdir (&c) facade for
os.stat + stat.S_ISDIR (&c)
Facade is a structural DP (we'll see another,
Adapter, later; in dbhash, they "merge"!-)
6
Design Patterns
7
What's a Design Pattern
8
summary of a frequent design problem +
structure of a solution to that problem +
pros and cons, alternatives, ..., and:
A NAME (much easier to retain/discuss!)
"descriptions of communicating objects and
classes customized to solve a general design
problem in a particular context"
DPs are NOT: data structures, algorithms,
domain-specific system architectures,
programming language features
MUST be studied in a language's context!
MUST supply Known Uses ("KU")
Many Good DP Books
9
(biblio on the last slide)
Classic DP Categories
Creational: ways and means of object
instantiation
Structural: mutual composition of classes or
objects (the Facade DP is Structural)
Behavioral: how classes or objects interact
and distribute responsibilities among them
Each can be class-level or object-level
10
Prolegomena to DPs
"program to an interface, not to an
implementation"
that's mostly done with "duck typing" in
Python -- rarely w/"formal" interfaces
actually similar to "signature-based
polymorphism" in C++ templates
11
Duck Typing Helps a Lot!
12
Teaching the ducks to type takes a while,
but saves you a lot of work afterwards!-)
Prolegomena to DPs
"favor object composition over class
inheritance"
in Python: hold, or wrap
inherit only when it's really convenient
expose all methods in base class (reuse
+ usually override + maybe extend)
but, it's a very strong coupling!
13
Python: hold or wrap?
14
Python: hold or wrap?
“Hold”: object O has subobject S as an
attribute (maybe property) -- that’s all
use self.S.method or O.S.method
simple, direct, immediate, but... pretty
strong coupling, often on the wrong axis
15
holder holdee
client
Python: hold or wrap?
“Wrap”: hold (often via private name) plus
delegation (so you directly use O.method)
explicit (def method(self...)...self.S.method)
automatic (delegation in __getattr__)
gets coupling right (Law of Demeter)
16
wrapper wrappee
client
class RestrictingWrapper(object):
def __init__(self, w, block):
self._w = w
self._block = block
def __getattr__(self, n):
if n in self._block:
raise AttributeError, n
return getattr(self._w, n)
...
Inheritance cannot restrict!
E.g: wrap to "restrict"
17
Creational Patterns
not very common in Python...
...because "factory" is essentially built-in!-)
18
Creational Patterns [1]
"we want just one instance to exist"
use a module instead of a class
no subclassing, no special methods, ...
make just 1 instance (no enforcement)
need to commit to "when" to make it
singleton ("highlander")
subclassing not really smooth
monostate ("borg")
Guido dislikes it
19
Singleton ("Highlander")
class Singleton(object):
def __new__(cls, *a, **k):
if not hasattr(cls, '_inst'):
cls._inst = super(Singleton, cls
).__new__(cls, *a, **k)
return cls._inst
subclassing is a problem, though:
class Foo(Singleton): pass
class Bar(Foo): pass
f = Foo(); b = Bar(); # ...???...
problem is intrinsic to Singleton
20
Monostate ("Borg")
class Borg(object):
_shared_state = {}
def __new__(cls, *a, **k):
obj = super(Borg, cls
).__new__(cls, *a, **k)
obj.__dict__ = cls._shared_state
return obj
subclassing is no problem, just:
class Foo(Borg): pass
class Bar(Foo): pass
class Baz(Foo): _shared_state = {}
data overriding to the rescue!
21
Creational Patterns [2]
"we don't want to commit to instantiating a
specific concrete class"
"Dependency Injection" DP
no creation except "outside"
what if multiple creations are needed?
"Factory" subcategory of DPs
may create w/ever or reuse existing
factory functions (& other callables)
factory methods (overridable)
abstract factory classes
22
Structural Patterns
"Masquerading/Adaptation" subcategory:
Adapter: tweak an interface (both class and
object variants exist)
Facade: simplify a subsystem's interface
...and many others I don't cover, such as:
Bridge: many implementations of an
abstraction, many implementations of a
functionality, no repetitive coding
Decorator: reuse+tweak w/o inheritance
Proxy: decouple from access/location
23
Adapter
client code γ requires a protocol C
supplier code σ provides different protocol
S (with a superset of C's functionality)
adapter code α "sneaks in the middle":
to γ, α is a supplier (produces protocol C)
to σ, α is a client (consumes protocol S)
"inside", α implements C (by means of
appropriate calls to S on σ)
24
Toy-example Adapter
C requires method foobar(foo, bar)
S supplies method barfoo(bar, foo)
e.g., σ could be:
class Barfooer(object):
def barfoo(self, bar, foo):
...
25
Object Adapter
per-instance, with wrapping delegation:
class FoobarWrapper(object):
def __init__(self, wrappee):
self.w = wrappee
def foobar(self, foo, bar):
return self.w.barfoo(bar, foo)
foobarer=FoobarWrapper(barfooer)
26
Class Adapter (direct)
per-class, w/subclasing & self-delegation:
class Foobarer(Barfooer):
def foobar(self, foo, bar):
return self.barfoo(bar, foo)
foobarer=Foobarer(...w/ever...)
27
Class Adapter (mixin)
flexible, good use of multiple inheritance:
class BF2FB:
def foobar(self, foo, bar):
return self.barfoo(bar, foo)
class Foobarer(BF2FB, Barfooer):
pass
foobarer=Foobarer(...w/ever...)
28
Adapter KU
socket._fileobject: from sockets to file-like
objects (w/much code for buffering)
doctest.DocTestSuite: adapts doctest tests
to unittest.TestSuite
dbhash: adapt bsddb to dbm
StringIO: adapt str or unicode to file-like
shelve: adapt "limited dict" (str keys and
values, basic methods) to complete mapping
via pickle for any <-> string
+ UserDict.DictMixin
29
Adapter observations
some RL adapters may require much code
mixin classes are a great way to help adapt
to rich protocols (implement advanced
methods on top of fundamental ones)
Adapter occurs at all levels of complexity
in Python, it's _not_ just about classes and
their instances (by a long shot!-) -- often
_callables_ are adapted (via decorators and
other HOFs, closures, functools, ...)
30
Facade vs Adapter
Adapter's about supplying a given protocol
required by client-code
or, gain polymorphism via homogeneity
Facade is about simplifying a rich interface
when just a subset is often needed
Facade most often "fronts" for a subsystem
made up of many classes/objects, Adapter
"front" for just one single object or class
31
Behavioral Patterns
Template Method: self-delegation
..."the essence of OOP"...
some of its many Python-specific variants
32
Template Method
great pattern, lousy name
"template" very overloaded
generic programming in C++
generation of document from skeleton
...
a better name: self-delegation
directly descriptive!-)
33
Classic TM
abstract base class offers "organizing
method" which calls "hook methods"
in ABC, hook methods stay abstract
concrete subclasses implement the hooks
client code calls organizing method
on some reference to ABC (injecter, or...)
which of course refers to a concrete SC
34
TM skeleton
class AbstractBase(object):
def orgMethod(self):
self.doThis()
self.doThat()
class Concrete(AbstractBase):
def doThis(self): ...
def doThat(self): ...
35
KU: cmd.Cmd.cmdloop
def cmdloop(self):
self.preloop()
while True:
s = self.doinput()
s = self.precmd(s)
finis = self.docmd(s)
finis = self.postcmd(finis,s)
if finis: break
self.postloop()
36
Classic TM Rationale
the "organizing method" provides
"structural logic" (sequencing &c)
the "hook methods" perform "actual
``elementary'' actions"
it's an often-appropriate factorization of
commonality and variation
focuses on objects' (classes')
responsibilities and collaborations: base
class calls hooks, subclass supplies them
applies the "Hollywood Principle": "don't
call us, we'll call you"
37
A choice for hooks
class TheBase(object):
def doThis(self):
# provide a default (often a no-op)
pass
def doThat(self):
# or, force subclass to implement
# (might also just be missing...)
raise NotImplementedError
Default implementations often handier, when
sensible; but "mandatory" may be good docs.
38
class Queue:
...
def put(self, item):
self.not_full.acquire()
try:
while self._full():
self.not_full.wait()
self._put(item)
self.not_empty.notify()
finally:
self.not_full.release()
def _put(self, item): ...
KU: Queue.Queue
39
Queue’s TMDP
Not abstract, often used as-is
thus, implements all hook-methods
subclass can customize queueing discipline
with no worry about locking, timing, ...
default discipline is simple, useful FIFO
can override hook methods (_init, _qsize,
_empty, _full, _put, _get) AND...
...data (maxsize, queue), a Python special
40
class LifoQueueA(Queue):
def _put(self, item):
self.queue.appendleft(item)
class LifoQueueB(Queue):
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = list()
def _get(self):
return self.queue.pop()
Customizing Queue
41
"Factoring out" the hooks
"organizing method" in one class
"hook methods" in another
KU: HTML formatter vs writer
KU: SAX parser vs handler
adds one axis of variability/flexibility
shades towards the Strategy DP:
Strategy: 1 abstract class per decision
point, independent concrete classes
Factored TM: abstract/concrete classes
more "grouped"
42
TM + introspection
"organizing" class can snoop into "hook"
class (maybe descendant) at runtime
find out what hook methods exist
dispatch appropriately (including "catch-
all" and/or other error-handling)
43
KU: cmd.Cmd.docmd
def docmd(self, cmd, a):
...
try:
fn = getattr(self, 'do_' + cmd)
except AttributeError:
return self.dodefault(cmd, a)
return fn(a)
44
Questions & Answers
45
Q?
A!
46
1.Design Patterns: Elements of Reusable Object-Oriented Software --
Gamma, Helms, Johnson, Vlissides -- advanced, very deep, THE classic
"Gang of 4" book that started it all (C++)
2.Head First Design Patterns -- Freeman -- introductory, fast-paced,
very hands-on (Java)
3.Design Patterns Explained -- Shalloway, Trott -- introductory, mix
of examples, reasoning and explanation (Java)
4.The Design Patterns Smalltalk Companion -- Alpert, Brown, Woolf
-- intermediate, very language-specific (Smalltalk)
5.Agile Software Development, Principles, Patterns and Practices --
Martin -- intermediate, extremely practical, great mix of theory and
practice (Java, C++)
6.Refactoring to Patterns -- Kerievsky -- introductory, strong
emphasis on refactoring existing code (Java)
7.Pattern Hatching, Design Patterns Applied -- Vlissides -- advanced,
anecdotal, specific applications of idea from the Gof4 book (C++)
8.Modern C++ Design: Generic Programming and Design Patterns
Applied -- Alexandrescu -- advanced, very language specific (C++)

Weitere ähnliche Inhalte

Was ist angesagt?

Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFDror Bereznitsky
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol Efe
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsSubhransu Behera
 
Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Guillaume Laforge
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 

Was ist angesagt? (19)

Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOF
 
Groovy 2.0 webinar
Groovy 2.0 webinarGroovy 2.0 webinar
Groovy 2.0 webinar
 
C#
C#C#
C#
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
 
Parte II Objective C
Parte II   Objective CParte II   Objective C
Parte II Objective C
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
C
CC
C
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013Lift off with Groovy 2 at JavaOne 2013
Lift off with Groovy 2 at JavaOne 2013
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Groovy 2 and beyond
Groovy 2 and beyondGroovy 2 and beyond
Groovy 2 and beyond
 
C tutorial
C tutorialC tutorial
C tutorial
 

Andere mochten auch

Andere mochten auch (17)

Yakub Sebastian_Visit_NTU_201405016v4
Yakub Sebastian_Visit_NTU_201405016v4Yakub Sebastian_Visit_NTU_201405016v4
Yakub Sebastian_Visit_NTU_201405016v4
 
Storbritannien en kort kurs med fakta om landet
Storbritannien en kort kurs med fakta om landetStorbritannien en kort kurs med fakta om landet
Storbritannien en kort kurs med fakta om landet
 
Cosapi unit 2 session 3
Cosapi  unit 2 session 3Cosapi  unit 2 session 3
Cosapi unit 2 session 3
 
Vi tror olika
Vi tror olikaVi tror olika
Vi tror olika
 
Cosapi unit 2 session 2
Cosapi  unit 2 session 2Cosapi  unit 2 session 2
Cosapi unit 2 session 2
 
Yaware product-sheet
Yaware product-sheetYaware product-sheet
Yaware product-sheet
 
Mosaik 4b
Mosaik 4bMosaik 4b
Mosaik 4b
 
Cosapi unit 2
Cosapi  unit 2Cosapi  unit 2
Cosapi unit 2
 
Cosapi unit 2 session 5 Categories of Materials
Cosapi  unit 2 session 5 Categories of MaterialsCosapi  unit 2 session 5 Categories of Materials
Cosapi unit 2 session 5 Categories of Materials
 
Creating the Performance Culture
Creating the Performance CultureCreating the Performance Culture
Creating the Performance Culture
 
Cosapi unit 2 session 8 Discussing Quality Issues
Cosapi  unit 2 session 8 Discussing Quality IssuesCosapi  unit 2 session 8 Discussing Quality Issues
Cosapi unit 2 session 8 Discussing Quality Issues
 
Begrepp i geografi europa
Begrepp i geografi europaBegrepp i geografi europa
Begrepp i geografi europa
 
Graffiti, exempel och instruktioner i två steg.
Graffiti, exempel och instruktioner i två steg.Graffiti, exempel och instruktioner i två steg.
Graffiti, exempel och instruktioner i två steg.
 
Transnet.+ lunch mt #1
Transnet.+ lunch mt #1Transnet.+ lunch mt #1
Transnet.+ lunch mt #1
 
Ff wiring
Ff wiringFf wiring
Ff wiring
 
Cosapi unit 2 session 9 Describing Component Features
Cosapi  unit 2 session 9 Describing Component FeaturesCosapi  unit 2 session 9 Describing Component Features
Cosapi unit 2 session 9 Describing Component Features
 
Ursvikens historia
Ursvikens historia Ursvikens historia
Ursvikens historia
 

Ähnlich wie Gdd pydp

Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patternsOlivier Bacs
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Groupbrada
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfAnassElHousni
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...GeeksLab Odessa
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentPython Ireland
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developersgeorgebrock
 
designpatterns_blair_upe.ppt
designpatterns_blair_upe.pptdesignpatterns_blair_upe.ppt
designpatterns_blair_upe.pptbanti43
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++Amresh Raj
 
Code snippets
Code snippetsCode snippets
Code snippetsSireesh K
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackDavid Sanchez
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxSRamadossbiher
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxSRamadossbiher
 

Ähnlich wie Gdd pydp (20)

Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patterns
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environment
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
C++ Boot Camp Part 2
C++ Boot Camp Part 2C++ Boot Camp Part 2
C++ Boot Camp Part 2
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
 
designpatterns_blair_upe.ppt
designpatterns_blair_upe.pptdesignpatterns_blair_upe.ppt
designpatterns_blair_upe.ppt
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Code snippets
Code snippetsCode snippets
Code snippets
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStack
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptx
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptx
 

Kürzlich hochgeladen

Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...anilsa9823
 
FULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | DelhiFULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | DelhiMalviyaNagarCallGirl
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...anilsa9823
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...wdefrd
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | Noida
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | NoidaFULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | Noida
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | Noidasoniya singh
 
Editorial sephora annual report design project
Editorial sephora annual report design projectEditorial sephora annual report design project
Editorial sephora annual report design projecttbatkhuu1
 
Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMroute66connected
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room servicediscovermytutordmt
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiMalviyaNagarCallGirl
 
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comBridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comthephillipta
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKedwardsara83
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboardthephillipta
 
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...akbard9823
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhisoniya singh
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...akbard9823
 
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Servicesonnydelhi1992
 
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service HisarVip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisarsrsj9000
 
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiMalviyaNagarCallGirl
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escortswdefrd
 

Kürzlich hochgeladen (20)

Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
 
FULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | DelhiFULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
FULL ENJOY - 9953040155 Call Girls in Wazirabad | Delhi
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | Noida
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | NoidaFULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | Noida
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Pari Chowk | Noida
 
Editorial sephora annual report design project
Editorial sephora annual report design projectEditorial sephora annual report design project
Editorial sephora annual report design project
 
Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NM
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room service
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
 
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.comBridge Fight Board by Daniel Johnson dtjohnsonart.com
Bridge Fight Board by Daniel Johnson dtjohnsonart.com
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
 
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
Bur Dubai Call Girls # 971504361175 # Call Girls In Bur Dubai || (UAE)
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboard
 
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
Aminabad @ Book Call Girls in Lucknow - 450+ Call Girl Cash Payment 🍵 8923113...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Vasant Kunj | Delhi
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
 
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Lajpat Nagar Delhi >༒9667401043 Escort Service
 
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service HisarVip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
Vip Hisar Call Girls #9907093804 Contact Number Escorts Service Hisar
 
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Sangam Vihar | Delhi
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
 

Gdd pydp

  • 1. Copyright ©2007, Google Inc Design Patterns in Python Alex Martelli (aleax@google.com) http://www.aleax.it/gdd_pydp.pdf
  • 2. The "levels" of this talk 2 Shu Ha Ri Py DP("Retain") ("Detach") ("Transcend")
  • 3. Hit the ground running... 3 "Forces": some rich, complex subsystem offers a lot of useful functionality; client code interacts with several parts of this functionality in a way that's "out of control" this causes many problems for client-code programmers AND subsystem ones too (complexity + rigidity)
  • 4. Solution: the "Facade" DP 4 interpose a simpler "Facade" object/class exposing a controlled subset of functionality client code now calls into the Facade, only the Facade implements its simpler functionality via calls into the rich, complex subsystem subsystem implementation gains flexibility, clients gain simplicity© 2004 AB Strakt 17 DP "Facade" ! existing supplier code ! provides ric complex functionality in protocol S ! we need a simpler "subset" C of S ! facade code " implements and supp (by calling S on !)
  • 5. Facade is a Design Pattern summary of a frequent design problem + structure of a solution to that problem (+ pros and cons, alternatives, ...), and: A NAME (much easier to retain/discuss!) "descriptions of communicating objects and classes customized to solve a general design problem in a particular context" that's NOT: a data structure, algorithm, domain-specific system architecture, programming-language/library feature MUST be studied in a language's context! MUST supply Known Uses ("KU") 5
  • 6. Some Facade KUs ...in the Python standard library...: dbhash facades for bsddb highly simplified/subset access also meets the "dbm" interface (thus, also an example of the Adapter DP) os.path: basename, dirname facade for split + indexing; isdir (&c) facade for os.stat + stat.S_ISDIR (&c) Facade is a structural DP (we'll see another, Adapter, later; in dbhash, they "merge"!-) 6
  • 8. What's a Design Pattern 8 summary of a frequent design problem + structure of a solution to that problem + pros and cons, alternatives, ..., and: A NAME (much easier to retain/discuss!) "descriptions of communicating objects and classes customized to solve a general design problem in a particular context" DPs are NOT: data structures, algorithms, domain-specific system architectures, programming language features MUST be studied in a language's context! MUST supply Known Uses ("KU")
  • 9. Many Good DP Books 9 (biblio on the last slide)
  • 10. Classic DP Categories Creational: ways and means of object instantiation Structural: mutual composition of classes or objects (the Facade DP is Structural) Behavioral: how classes or objects interact and distribute responsibilities among them Each can be class-level or object-level 10
  • 11. Prolegomena to DPs "program to an interface, not to an implementation" that's mostly done with "duck typing" in Python -- rarely w/"formal" interfaces actually similar to "signature-based polymorphism" in C++ templates 11
  • 12. Duck Typing Helps a Lot! 12 Teaching the ducks to type takes a while, but saves you a lot of work afterwards!-)
  • 13. Prolegomena to DPs "favor object composition over class inheritance" in Python: hold, or wrap inherit only when it's really convenient expose all methods in base class (reuse + usually override + maybe extend) but, it's a very strong coupling! 13
  • 14. Python: hold or wrap? 14
  • 15. Python: hold or wrap? “Hold”: object O has subobject S as an attribute (maybe property) -- that’s all use self.S.method or O.S.method simple, direct, immediate, but... pretty strong coupling, often on the wrong axis 15 holder holdee client
  • 16. Python: hold or wrap? “Wrap”: hold (often via private name) plus delegation (so you directly use O.method) explicit (def method(self...)...self.S.method) automatic (delegation in __getattr__) gets coupling right (Law of Demeter) 16 wrapper wrappee client
  • 17. class RestrictingWrapper(object): def __init__(self, w, block): self._w = w self._block = block def __getattr__(self, n): if n in self._block: raise AttributeError, n return getattr(self._w, n) ... Inheritance cannot restrict! E.g: wrap to "restrict" 17
  • 18. Creational Patterns not very common in Python... ...because "factory" is essentially built-in!-) 18
  • 19. Creational Patterns [1] "we want just one instance to exist" use a module instead of a class no subclassing, no special methods, ... make just 1 instance (no enforcement) need to commit to "when" to make it singleton ("highlander") subclassing not really smooth monostate ("borg") Guido dislikes it 19
  • 20. Singleton ("Highlander") class Singleton(object): def __new__(cls, *a, **k): if not hasattr(cls, '_inst'): cls._inst = super(Singleton, cls ).__new__(cls, *a, **k) return cls._inst subclassing is a problem, though: class Foo(Singleton): pass class Bar(Foo): pass f = Foo(); b = Bar(); # ...???... problem is intrinsic to Singleton 20
  • 21. Monostate ("Borg") class Borg(object): _shared_state = {} def __new__(cls, *a, **k): obj = super(Borg, cls ).__new__(cls, *a, **k) obj.__dict__ = cls._shared_state return obj subclassing is no problem, just: class Foo(Borg): pass class Bar(Foo): pass class Baz(Foo): _shared_state = {} data overriding to the rescue! 21
  • 22. Creational Patterns [2] "we don't want to commit to instantiating a specific concrete class" "Dependency Injection" DP no creation except "outside" what if multiple creations are needed? "Factory" subcategory of DPs may create w/ever or reuse existing factory functions (& other callables) factory methods (overridable) abstract factory classes 22
  • 23. Structural Patterns "Masquerading/Adaptation" subcategory: Adapter: tweak an interface (both class and object variants exist) Facade: simplify a subsystem's interface ...and many others I don't cover, such as: Bridge: many implementations of an abstraction, many implementations of a functionality, no repetitive coding Decorator: reuse+tweak w/o inheritance Proxy: decouple from access/location 23
  • 24. Adapter client code γ requires a protocol C supplier code σ provides different protocol S (with a superset of C's functionality) adapter code α "sneaks in the middle": to γ, α is a supplier (produces protocol C) to σ, α is a client (consumes protocol S) "inside", α implements C (by means of appropriate calls to S on σ) 24
  • 25. Toy-example Adapter C requires method foobar(foo, bar) S supplies method barfoo(bar, foo) e.g., σ could be: class Barfooer(object): def barfoo(self, bar, foo): ... 25
  • 26. Object Adapter per-instance, with wrapping delegation: class FoobarWrapper(object): def __init__(self, wrappee): self.w = wrappee def foobar(self, foo, bar): return self.w.barfoo(bar, foo) foobarer=FoobarWrapper(barfooer) 26
  • 27. Class Adapter (direct) per-class, w/subclasing & self-delegation: class Foobarer(Barfooer): def foobar(self, foo, bar): return self.barfoo(bar, foo) foobarer=Foobarer(...w/ever...) 27
  • 28. Class Adapter (mixin) flexible, good use of multiple inheritance: class BF2FB: def foobar(self, foo, bar): return self.barfoo(bar, foo) class Foobarer(BF2FB, Barfooer): pass foobarer=Foobarer(...w/ever...) 28
  • 29. Adapter KU socket._fileobject: from sockets to file-like objects (w/much code for buffering) doctest.DocTestSuite: adapts doctest tests to unittest.TestSuite dbhash: adapt bsddb to dbm StringIO: adapt str or unicode to file-like shelve: adapt "limited dict" (str keys and values, basic methods) to complete mapping via pickle for any <-> string + UserDict.DictMixin 29
  • 30. Adapter observations some RL adapters may require much code mixin classes are a great way to help adapt to rich protocols (implement advanced methods on top of fundamental ones) Adapter occurs at all levels of complexity in Python, it's _not_ just about classes and their instances (by a long shot!-) -- often _callables_ are adapted (via decorators and other HOFs, closures, functools, ...) 30
  • 31. Facade vs Adapter Adapter's about supplying a given protocol required by client-code or, gain polymorphism via homogeneity Facade is about simplifying a rich interface when just a subset is often needed Facade most often "fronts" for a subsystem made up of many classes/objects, Adapter "front" for just one single object or class 31
  • 32. Behavioral Patterns Template Method: self-delegation ..."the essence of OOP"... some of its many Python-specific variants 32
  • 33. Template Method great pattern, lousy name "template" very overloaded generic programming in C++ generation of document from skeleton ... a better name: self-delegation directly descriptive!-) 33
  • 34. Classic TM abstract base class offers "organizing method" which calls "hook methods" in ABC, hook methods stay abstract concrete subclasses implement the hooks client code calls organizing method on some reference to ABC (injecter, or...) which of course refers to a concrete SC 34
  • 35. TM skeleton class AbstractBase(object): def orgMethod(self): self.doThis() self.doThat() class Concrete(AbstractBase): def doThis(self): ... def doThat(self): ... 35
  • 36. KU: cmd.Cmd.cmdloop def cmdloop(self): self.preloop() while True: s = self.doinput() s = self.precmd(s) finis = self.docmd(s) finis = self.postcmd(finis,s) if finis: break self.postloop() 36
  • 37. Classic TM Rationale the "organizing method" provides "structural logic" (sequencing &c) the "hook methods" perform "actual ``elementary'' actions" it's an often-appropriate factorization of commonality and variation focuses on objects' (classes') responsibilities and collaborations: base class calls hooks, subclass supplies them applies the "Hollywood Principle": "don't call us, we'll call you" 37
  • 38. A choice for hooks class TheBase(object): def doThis(self): # provide a default (often a no-op) pass def doThat(self): # or, force subclass to implement # (might also just be missing...) raise NotImplementedError Default implementations often handier, when sensible; but "mandatory" may be good docs. 38
  • 39. class Queue: ... def put(self, item): self.not_full.acquire() try: while self._full(): self.not_full.wait() self._put(item) self.not_empty.notify() finally: self.not_full.release() def _put(self, item): ... KU: Queue.Queue 39
  • 40. Queue’s TMDP Not abstract, often used as-is thus, implements all hook-methods subclass can customize queueing discipline with no worry about locking, timing, ... default discipline is simple, useful FIFO can override hook methods (_init, _qsize, _empty, _full, _put, _get) AND... ...data (maxsize, queue), a Python special 40
  • 41. class LifoQueueA(Queue): def _put(self, item): self.queue.appendleft(item) class LifoQueueB(Queue): def _init(self, maxsize): self.maxsize = maxsize self.queue = list() def _get(self): return self.queue.pop() Customizing Queue 41
  • 42. "Factoring out" the hooks "organizing method" in one class "hook methods" in another KU: HTML formatter vs writer KU: SAX parser vs handler adds one axis of variability/flexibility shades towards the Strategy DP: Strategy: 1 abstract class per decision point, independent concrete classes Factored TM: abstract/concrete classes more "grouped" 42
  • 43. TM + introspection "organizing" class can snoop into "hook" class (maybe descendant) at runtime find out what hook methods exist dispatch appropriately (including "catch- all" and/or other error-handling) 43
  • 44. KU: cmd.Cmd.docmd def docmd(self, cmd, a): ... try: fn = getattr(self, 'do_' + cmd) except AttributeError: return self.dodefault(cmd, a) return fn(a) 44
  • 46. 46 1.Design Patterns: Elements of Reusable Object-Oriented Software -- Gamma, Helms, Johnson, Vlissides -- advanced, very deep, THE classic "Gang of 4" book that started it all (C++) 2.Head First Design Patterns -- Freeman -- introductory, fast-paced, very hands-on (Java) 3.Design Patterns Explained -- Shalloway, Trott -- introductory, mix of examples, reasoning and explanation (Java) 4.The Design Patterns Smalltalk Companion -- Alpert, Brown, Woolf -- intermediate, very language-specific (Smalltalk) 5.Agile Software Development, Principles, Patterns and Practices -- Martin -- intermediate, extremely practical, great mix of theory and practice (Java, C++) 6.Refactoring to Patterns -- Kerievsky -- introductory, strong emphasis on refactoring existing code (Java) 7.Pattern Hatching, Design Patterns Applied -- Vlissides -- advanced, anecdotal, specific applications of idea from the Gof4 book (C++) 8.Modern C++ Design: Generic Programming and Design Patterns Applied -- Alexandrescu -- advanced, very language specific (C++)