Design Patterns are from the book:
Some references are from the book:
Note:
The term interface means application programming interface (API), unless stated otherwise.
  Purpose
  Creational Structural Behavioral
Scope Class
Object
         
Factory Method
(class, creational)
Factory Method Structure
Intent
  • Define an interface for creating an object, but let subclasses decide which class to instantiate
  • Let a class defer instantiation to subclasses
Example(s)
  • Create different loggers (e.g. file, console, database, etc) through inheritance
Advantage(s)
  • Eliminate the need to bind application-specific classes, hence can work with any user-defined ConcreteProduct classes
  • Is more flexible than creating an object directly
  • Give subclasses a hook for providing an extended version of an object
  • Connect parallel class hierarchies so that class delegates some of its responsibilities to a separate class
Disadvantage(s)
  • Clients may have to subclass Creator class just to create particular ConcreteProduct object
Top
Abstract Factory
(object, creational)
Abstract Factory Structure
Intent
  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes
Example(s)
  • Create different look-and-feel (Windows, Mac, etc) user interfaces
  • Create JDBC related objects (Connection, Statement, ResultSet, etc)
Advantage(s)
  • Isolate clients from concrete (implementation) classes, clients manipulate instances through their abstract interfaces
  • Make exchanging product families easy, concrete factory appears only once
  • Promote consistency among products, enforce application to use objects from only one family at a time
Disadvantage(s)
  • Difficult to support new kinds of products, adding new products requires changing abstract factory class and all its subclasses
Top
Builder
(object, creational)
Builder Structure
Intent
  • Separate the construction of a complex object from its representation so that the same construction process can create different representations
Example(s)
  • Create a computer object part by part (e.g. HDD, RAM, etc)
  • Create a car object part by part (e.g. engine, seats, etc)
  • Create a search screen object part by part (e.g. drop-downs, text boxes, etc)
  • Create an order object part by part (e.g. billing address, shipping address, order items, fees, etc)
Advantage(s)
  • Allow developer to vary a product's internal representation
  • Isolate code for construction and representation
  • Give developer finer control over construction process
Disadvantage(s)
  • Code may become verbose
Top
Prototype
(object, creational)
Prototype Structure
Intent
  • Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype
Example(s)
  • Create musical notes for music scores
  • Create circuit components
  • Create new software programs
  • Create cover letters
Advantage(s)
  • Able to add and remove products at run-time
  • Specify new objects by varying values and/or structures
  • Reduce the number of subclasses
  • Able to configure classes dynamically
Disadvantage(s)
Top
Singleton
(object, creational)
Singleton Structure
Implement with (synchronized) private constructor
Intent
  • Ensure a class only has one instance, and provide a global point of access to it
Example(s)
  • Database connection (pool)
  • Printer spool queue
  • Common data/ log file
Advantage(s)
  • Controlled access to sole instance (strict control how and when clients access it)
  • Reduced name space (avoid polluting name space with global variables)
  • Allow refinement to operations and representation
  • More flexible than class (static) operations
Disadvantage(s)
  • Cannot be subclassed
Top
Adapter
(class/object, structural)
Class adapter
Adapter (Class) Structure
Object adapter
Adapter (Object) Structure Class vs Object Adapters
Intent
  • Convert the interface of a class into another interface clients expect
  • Let classes work together that could not otherwise because of incompatible interfaces
Example(s)
  • Mobile phone charger (support 120V and 240V)
  • Address validation (support for say addresses in USA and China)
Advantage(s)
Class adapter
  • Let Adapter overrides some of Adaptee's behavior
  • Introduce only one object
  • Adapt Adaptee to Target by committing to concrete Adapter class (will not work when developer wants to adapt a class and its subclasses)
Object adapter
  • Let single Adapter to work with many Adaptees
Disadvantage(s)
Class adapter
  • May increase number of classes and/or duplicating code because of inheritance
Object adapter
  • Cannot override Adaptee's behavior because of composition
Top
Bridge
(object, structural)
Bridge Structure
Intent
  • Decouple an abstraction from its implementation so that the two can vary independently
Example(s)
  • Drawing various shapes (e.g. circles) with different attributes (e.g. color, radius)
  • Code formatting (e.g. text, HTML, color)
Advantage(s)
  • Decouple Abstraction and Implementor
  • Improve extensibility (for both Abstraction and Implementor)
  • Hide implementation details from clients
Disadvantage(s)
  • May be hard to determine how, when and where to instantiate the Implementor object
Top
Composite
(object, structural)
Composite Structure
Intent
  • Compose objects into tree structures to represent part-whole hierarchies
  • Let clients treat individual objects and compositions of objects uniformly
Example(s)
  • Folder/File structure
Advantage(s)
  • Define class hierarchy consisting of primitive objects and composite objects (primitive objects can become composite objects)
  • Make clients simpler (clients treat Composite and Leaf objects uniformly)
  • Make it easier to add new kinds of components (clients do not have to be changed for Component objects)
Disadvantage(s)
  • Can make design overly general
Top
Decorator
(object, structural)
Decorator Structure
Intent
  • Attach additional responsibilities to an object dynamically
  • Provide a flexible alternative to subclassing for extending functionality
Example(s)
  • Create different loggers (e.g. file, console, database, etc) through composition
  • Add borders or scroll bars to text views
Advantage(s)
  • More flexible than static inheritance (add/remove responsibility at run-time)
  • Avoid feature-laden classes high up in the hierarchy; offer pay-as-you-go approach to adding responsibilities
Disadvantage(s)
  • Decorator is not identical to its Component (cannot rely on object identity)
  • Can have many little objects becoming hard to maintain
Top
Façade
(object, structural)
Façade Structure
Intent
  • Provide a unified interface to a set of interfaces in a subsystem
  • Define a higher-level interface that makes the subsystem easier to use
Example(s)
  • Buying items online (subsystem containing Account, Address, CreditCard, etc)
Advantage(s)
  • Shield clients from subsystem components, reducing the number of objects clients need to deal with
  • Promote loose coupling between clients and subsystem (eliminate complex and/or circular dependencies)
Disadvantage(s)
  • Do not prevent applications from using subsystem classes directly
Top
Flyweight
(object, structural)
Flyweight Structure
FlyweightFactory is a singleton
Intent
  • Use sharing to support large numbers of fine-grained objects efficiently
Example(s)
  • Displaying employee information (common/intrinsic attributes/data as flyweight object) in visitor passes
  • Showing characters (from a flyweight pool) in rows/columns of an editor
Advantage(s)
  • Save space as more flyweight objects are shared
Disadvantage(s)
  • May introduce run-time costs
Top
Proxy
(object, structural)
Proxy Structure
Intent
  • Provide a surrogate or placeholder for another object to control access to it
Example(s)
  • Load an image on demand (virtual proxy)
  • Access resource in different address space (remote proxy)
  • Control access to resources (protection proxy)
Advantage(s)
  • Introduce a level of indirection when accessing objects
Disadvantage(s)
  • May not know the type of RealSubject
Top
Interpreter
(class, behavioral)
Interpreter Structure
Intent
  • Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language
Example(s)
  • Parsing regular expressions
  • Evaluating logical expressions (e.g. AND, OR, NOT, etc)
Advantage(s)
  • Easy to change and extend the grammar
  • Easy to implement the grammar
  • Able to add new ways to interpret expressions
Disadvantage(s)
  • Hard to maintain for complex grammar
Top
Template Method
(class, behavioral)
Template Method Structure
Intent
  • Define the skeleton of an algorithm in an operation, deferring some steps to subclasses
  • Let subclasses redefine certain steps of an algorithm without changing the algorithm's structure
Example(s)
  • Credit card validation (e.g. check expiry date in template method)
Advantage(s)
  • Avoid code duplication
  • Use inheritance, not composition (subclasses overriding the necessary methods)
  • Make use of polymorphism
Disadvantage(s)
  • May be difficult to determine if subclasses should override methods (from base class) or not
Top
Chain of Responsibility
(object, behavioral)
Chain of Responsibility Structure
Intent
  • Avoid 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
Example(s)
  • Purchase authorization (branch manager → regional director → vice president → president)
  • Exception handling in Java
Advantage(s)
  • Reduce coupling between sender and receiver
  • Able to add flexibility in assigning responsibilities to objects
Disadvantage(s)
  • Receipt is not guaranteed (request may not be handled or fall off chain)
Top
Command
(object, behavioral)
Command Structure
Intent
  • Encapsulate a request as an object, thereby letting developer parameterize clients with different requests, queue or log requests, and support undoable operations
Example(s)
  • Button click
  • Menu item click
  • java.util.EventListener and its sub-interfaces
Advantage(s)
  • Decouple the object that invokes the operation from the one that knows how to perform it
  • First-class objects hence can be extended
  • Can assemble into a composite command
  • Easy to add new commands
Disadvantage(s)
  • Need to keep state for undo/redo commands
Top
Iterator
(object, behavioral)
Iterator Structure
Intent
  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation
Example(s)
  • java.sql.ResultSet (internal)
  • java.util.ListIterator (external)
Advantage(s)
  • Support variations of traversals of Aggregate (forward and/or backward)
  • Support traversal of Aggregate
  • Can have more than one traversal over Aggregate
Disadvantage(s)
  • Can be dangerous to modify Aggregate while traversing it
Top
Mediator
(object, behavioral)
Mediator Structure
Intent
  • Define an object that encapsulates how a set of objects interact
  • Promote loose coupling by keeping objects from referring to each other explicitly, enabling developer to vary the interaction(s) independently
Example(s)
  • Router (as the mediator) delivering packets to different computers
Advantage(s)
  • Decouple Colleagues
  • Simplify object protocol (replace many-to-many with one-to-many interactions)
  • Abstract how objects cooperate
Disadvantage(s)
  • Limit subclassing for Mediators
Top
Memento
(object, behavioral)
Memento Structure
Intent
  • Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later
Example(s)
  • Serialization and de-serialization of objects
  • Passivation and activation of stateful EJBs
Advantage(s)
  • Preserve encapsulation boundary
  • Simplify Originator
Disadvantage(s)
  • Using memento may be expensive (e.g. memory, storage)
  • May be difficult to ensure Originator can access Memento's state
  • Caretaker may incur large storage costs
Top
Observer
(object, behavioral)
Observer Structure
Intent
  • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
Example(s)
  • Models trigger updates in views under MVC frameworks
Advantage(s)
  • Able to vary Subjects and Observers independently
  • Abstract coupling between Subjects and Observers (all Subject knows is that it has a list of Observers)
  • Support for broadcast communication
Disadvantage(s)
  • Unexpected updates (Observers have no knowledge of each other's presence)
Top
State
(object, behavioral)
State Structure
Intent
  • Allow an object to alter its behavior when its internal state changes; the object will appear to change its class
Example(s)
  • Vending machines (e.g. product out of stock, give change after purchase, etc)
  • java.lang.Thread.State (e.g. NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED)
Advantage(s)
  • Make state transition explicit
  • State objects can be shared (hence flyweights)
  • Localize state-specific behavior and partition behavior for different states
Disadvantage(s)
  • May increase number of ConcreteState classes
Top
Strategy
(object, behavioral)
Strategy Structure
Intent
  • Define a family of algorithms, encapsulate each one, and make them interchangeable
  • Let the algorithm vary independently from clients that use it
Example(s)
  • Displaying messages with various encryption algorithms
Advantage(s)
  • Families of related algorithms
  • Alternative to subclassing
  • Eliminate conditional statements
  • Client has choice of implementations
Disadvantage(s)
  • Clients must be aware of different Strategies
  • Communication overhead between Strategy and Context
  • May increase number of objects
Top
Visitor
(object, behavioral)
Visitor Structure
Intent
  • Represent an operation to be performed on the elements of an object structure
  • Let developer to define a new operation without changing the classes of the elements on which it operates
Example(s)
  • Calculate size of folder/file structure
  • Get total amounts for various order objects
Advantage(s)
  • Easy to add new operations
  • Gather related operations and separate unrelated ones
  • Able to traverse different class hierarchies or types
Disadvantage(s)
  • Hard to add new ConcreteElements
  • Accumulate state as Visitors traverse each element in the object structure
  • May break encapsulation, provide public operations to access element's internal state
Top

Shallow Copy vs Deep Copy

Shallow Copy Deep Copy
Original top-level object and all of its primitive members are duplicated Original top-level object and all of its primitive members are duplicated
Any lower-level objects that the top-level object contains are not duplicated (only references to these objects are copied) Any lower-level objects that the top-level object contains are also duplicated
Result in original object and cloned object refer to same copy of lower-level object
Shallow Copy
Result in original object and cloned object refer to different copy of lower-level object
Deep Copy
Prototype
Top

Class vs Object Adapters

Class Adapters Object Adapters
Based on the concept of inheritance Use object composition
Can override some of the adaptee's methods Cannot override adaptee's methods
Can be used to adapt the interface of the adaptee only but cannot adapt the interfaces of its subclasses because the adapter is statically linked with the adaptee when it is created Can be used to adapt the interface of the adaptee and all of its subclasses
The client will have some knowledge of the adaptee's interface as the full public interface of the adaptee is visible to the client The client and the adaptee are completely decoupled; only the adapter is aware of the adaptee's interface
Adapter
Top

Internal vs External Iterators

Internal Iterators External Iterators
Iteration functionality (methods such as next, hasNext) is within the collection Iteration functionality (methods such as next, hasNext) is separated from the collection; collection usually returns an appropriate iterator to the client
Only one iterator on a given collection at any given time Multiple iterators on a given collection at any given time
Collection needs to maintain or save the state of iteration Collection does not need to maintain or save the state of iteration
Iterator
Top