Monday, February 12, 2007

GoF Design Patterns

Motivation and Purpose
  • Encapsulate internal state of objects.
    • Distinguish intrinsic state from extrinsic state.
  • Decompose a system into abstractions.
    • Delegation works best when used in highly stylized ways (i.e. design patterns).
  • Principles of reusable object-oriented design:
    • Program to an interface, not an implementation. (Use loose coupling.)
    • Favor object composition over class inheritance. (Use delegation.)
  • Techniques for designing for change:
    • Avoid dependency on type of implementation class.
    • Avoid dependency on specific operation dispatch.
    • Increase information hiding.
    • Increase algorithm hiding.
    • Decrease tight coupling; increase loose coupling.
    • Increase flexibility by using object composition in general and delegation in particular instead of subclassing.
    • Alter behavior of a library class without modifying the library.
Examples of design patterns in Java:

Creational Patterns
  • Abstract Factory -- BorderFactory, Collections, org.w3c.dom.Document (create methods)
  • Builder -- StringBuilder, ProcessBuilder
  • Factory Method -- URLStreamHandlerFactory, InitialContextFactory
  • Prototype -- (copyable state objects for supporting cancelable UI)
  • Singleton -- java.lang.Runtime
Structural Patterns
  • Adapter -- InputStreamReader, OutputStreamWriter
  • Bridge -- Swing PLAF
  • Composite -- java.awt.Component/Container
  • Decorator -- BufferedReader/Writer, ZipInputStream, other java.io classes
  • Facade -- what Swing is to java.awt.Graphics
  • Flyweight -- Icon (when cached)
  • Proxy -- RMI, WeakReference, ThreadLocal
Behavioral Patterns
  • Chain of Responsibility -- KeyEvent dispatch in AWT/Swing (consume() method stops chain)
  • Command -- javax.swing.Action (not quite - need a better example)
  • Interpreter -- java.util.regex.Pattern
  • Iterator
  • Mediator -- event cascades
  • Memento --javax.swing.undo.UndoableEdit, java.awt.datatransfer.Transferable, java.beans.XMLEncoder/Decoder
  • Observer -- Swing/AWT event listeners
  • State -- graphical tools (e.g. from a component palette) used in a visual editor
  • Strategy -- dispatch of Undo; typical pattern for View-Controller interaction
  • Template Method -- java.io.Reader/Writer
  • Visitor -- SAX API (org.xml.sax)

No comments: