View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide
Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

Design Pattern Handbook

Edit Design Pattern Handbook here.


This is meant to be a supplemental reference to understand the basic ideas behind design patterns that could benefit you in CS2340. An excellent reference for design patterns is the book entitled “Design Patterns Elements of Reusable Object-Oriented Software” written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. This book is useful for this class as it contains Smalltalk examples. The ISBN is 0-201-63361-2.
These three categories are Creational patterns, Structural patterns, and Behavioral patterns. I have gone through each pattern within the subcategories to define the basic idea behind the patterns.
First of all, you should know why design patterns exist. A design pattern is a proven solution for common problems encountered during the design process. Since it is a proven method, it captures design expertise and helps the designer facilitate requirements with the most efficient design possible.

Creational Design Patterns are design patterns that deal with instantiation of objects. Since this class is using Smalltalk and everything is an object you will have to use delegation to get the object instantiated. The following fall under this category.

Abstract Factory: The factory determines the actual concrete type of object to be created and creates it. The best method to do this is to have the factory return an abstract pointer to the actual object that was created. Abstraction lets you focus on the bigger picture and worry about the details later. This design principle enables you to do this while creating objects. Similar to the other creational patterns, this design enables the designer to deal with the issue of creating objects without specifying the exact class that needs to be created. This method is common in programs where library code needs to create objects of types which may be sub classed by the application. It is also common for parallel hierarchies that often require objects from one hierarchy to be able to create appropriate objects from another hierarchy.
How to do it: You define a separate method for creating objects, which subclasses can override to specify the derived type of object to be created.
Example: Using a pasta maker as an analogy I will attempt to explain in more detail. A pasta maker will produce different types of pasta, depending what kind of disk is loaded into the machine. All disks should have certain properties in common, so that they will work with the pasta maker. This specification for the disks is the Abstract Factory, and each specific disk is a Factory. You will never see an Abstract Factory, because one can never exist, but all Factories (pasta maker disks) inherit their properties from the abstract Factory. In this way, all disks will work in the pasta maker, since they all comply with the same specifications. The pasta maker doesn't care what the disk is doing, nor should it. You turn the handle on the pasta maker, and the disk makes a specific shape of pasta come out. Each individual disk contains the information of how to create the pasta, and the pasta maker does not.


Builder: The objective is to separate the construction of complex objects from it’s representation so that the initial construction process will be able to create multiple and/or different representations. The factory pattern defers the decision of what concrete type of object to make until run time.
How to do it: The builder pattern encapsulates the logic of how to put together a complex object so that the client just requests a configuration and the builder directs the logic of building it.
Example: The main contractor (builder) in building a house knows, given a floor plan, how to execute the sequence of operations (i.e. by delegating to subcontractors) needed to build the complex object. If that logic was not encapsulated in a builder, then the buyers would have to organize the subcontracting themselves ("Dear, shouldn't we have asked for the foundation to be laid before the roofers showed up?"). The factory is concerned with what is made, the builder with how it is made.
The design patterns points out that Abstract factory is similar to builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract factory's emphasis is on families of product objects (either simple or complex). Builder returns the product as the final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

Prototype: A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used for example when the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) is prohibitively expensive for a given application.
How to do it: To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation. The client, instead of writing code that invokes the "new" operator on a hard-wired class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern.
Example: The Prototype pattern specifies the kind of objects to create using a prototypical instance. Prototypes of new products are often built prior to full production, but in this example, the prototype is passive, and does not participate in copying itself. The mitotic division of a cell, resulting in two identical cells, is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.

Singleton: This is used to restrict instantiation of a class to one object. It is only useful when exactly one object is needed to coordinate relationships across the system. Some consider it an anti-pattern since it is often used to describe a global variable.
How to do it: Make constructor private, make static accessor methods.
Example: The Singleton pattern is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, "The President of the United States" is a global point of access that identifies the person in the office.

Structural Design Patterns deal with object composition. Inheritance is the best way to compose the interfaces and define how objects will be composed/created to attain new functionality. The following fall under this category.

Adapter a.k.a. Wrapper: Adapt one interface for a class into one that a client expects.
How to do it: An adapter allows classes to work together that normally could not because of incompatible interfaces by wrapping its own interface around that of an already existing class. There are two types of adapter patterns:
1.The Object Adapter pattern - In this type of adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to a physical instance of the wrapped object.
2. The Class Adapter pattern - This type of adapter uses multiple inheritances to achieve its goal. The adapter is created inheriting interfaces from both the interface that is expected and the interface that is pre-existing. The Object Adapter pattern is more often used, as some popular languages, such as Java, do not support true multiple inheritances as the designers of these languages consider it a dangerous practice.
Example: The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients. Socket wrenches provide an example of the Adapter. A socket attaches to a ratchet, provided that the size of the drive is the same. Typical drive sizes in the United States are 1/2" and 1/4". Obviously a 1/2" drive ratchet will not fit into a 1/4" drive socket unless an adapter is used. A 1/2" to 1/4" adapter has a 1/2" female connection to fit on the 1/2" drive ratchet, and a 1/4" male connection to fit in the 1/4" drive socket.

Bridge: Decouple an abstraction from it’s implementation so that the two can vary independently.
How to do it: The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when not only the class itself varies often but also what the class does. The class itself can be thought of as the abstraction and what the class can do as the implementation.
Example: The Bridge pattern decouples an abstraction from its implementation, so that the two can vary independently. A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be implemented as a pull chain, a simple two-position switch, or a variety of dimmer switches.

Composite: A tree structure of objects where every object has the same interface.
How to do it: There are four parts.
1. Component class/object will declare the interface for object composition, implement default behavior, and declare an interface for accessing and managing the child components.
2. Leaf class/object will represent leaf objects in the composition.
3. Composite class/object will define behavior for components having children, store child components, and implement child-related operations to the Component interface.
4. Client class/object will manipulate objects in the composition through the Component interface.
Example: The Composite composes objects into tree structures, and lets clients treat individual objects and compositions uniformly. Although the example is abstract, arithmetic expressions are Composites. An arithmetic expression consists of an operand, an operator (+ - x/), and another operand. The operand can be a number, or another arithmetic expression. Thus, 2 + 3 and (2 + 3) + (4x 6) are both valid expressions.

Decorator: Add additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes.
How to do it: The decorator pattern works by wrapping the new "decorator" object around the original object, which is typically achieved by passing the original object as a parameter to the constructor of the decorator, with the decorator implementing the new functionality. The interface of the original object needs to be maintained by the decorator.
Example: The Decorator attaches additional responsibilities to an object dynamically. Although paintings can be hung on a wall with or without frames, frames are often added, and it is the frame, which is actually hung on the wall. Prior to hanging, the paintings may be matted and framed, with the painting, matting, and frame forming a single visual component.

Façade: Creates a simplified interface of an existing interface to ease usage for common tasks. A façade will be able to do the following:
1. Make a software library easier to use and understand, since the façade has convenient methods for common tasks.
2. Make code that uses the library more readable, for the same reason.
3. Reduce dependencies of outside code on the inner workings of a library, since most code uses the façade, thus allowing more flexibility in developing the system.
4. Wrap a poorly designed collection of APIs with a single well-designed API.
How to do it: Interpose an articulation point A: a class that presents a stable interface to clients, but which translates a client's requests to control B into B's [possibly unstable] interface.
Example: The Facade defines a unified, higher-level interface to a subsystem that makes it easier to use. Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department.

Flyweight: A high quantity of objects share a common properties object to save space.
How to do it: In the flyweight pattern, the data has no pointers to the data type methods, because these would consume too much space. Instead, the subroutines are called directly. In some cases, “shift-in and shift-out” data markers perform flyweight inheritance as a higher-level operation cycles through an array of flyweight data.
Example: The Flyweight uses sharing to support large numbers of objects efficiently. The public switched telephone network is an example of a Flyweight. There are several resources such as dial tone generators, ringing generators, and digit receivers that must be shared between all subscribers. A subscriber is unaware of how many resources are in the pool when he or she lifts the hand set to make a call. All that matters to subscribers is that dial tone is provided, digits are received, and the call is completed.

Proxy: A class functioning as an interface to another thing.
How to do it: The proxy pattern can be used in situations where multiple copies of a complex object must exist. In order to reduce the application's memory footprint in such situations, one instance of the complex object is created, and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.
Example: The Proxy provides a surrogate or place holder to provide access to an object. A check or bank draft is a proxy for funds in an account. A check can be used in place of cash for making purchases and ultimately controls access to cash in the issuer's account.

Behavioral patterns focus on the interaction/communication between existing objects. The following fall under this category.

Chain of responsibility: Design pattern consisting of a source of command objects and a series of processing objects.
How to do it: Each processing object contains a set of logic that describes the types of command objects that it can handle, and how to pass off those that it cannot to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
Example: The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver, by giving more than one object a chance to handle the request. Mechanical coin sorting banks use the Chain of Responsibility. Rather than having a separate slot for each coin denomination coupled with receptacle for the denomination, a single slot is used. When the coin is dropped, the coin is routed to the appropriate receptacle by the mechanical mechanisms within the bank.

Command: Design pattern in which objects are used to represent actions.
How to do it: A command object encapsulates an action and its parameters.

Example: The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parameterized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order, or command from a customer, and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of "checks" used by different diners is not dependent on the menu, and therefore they can support commands to cook many different items.

Interpreter: The basic idea is to implement a specialized computer language to rapidly solve a defined class of problems. Specialized languages often let a problem be solved several to several hundred times more quickly than a general-purpose language would permit.
How to do it: Use a class to represent each primitive and each combination rule. Represent a problem with a tree whose leaves are primitive objects and whose internal nodes are combination rule objects. Solve the problem by traversing the tree. Each node has a method, which receives the traversal state and performs some work, possibly modifying the traversal state or delegating some of the work to children. Calling the root node with the initial traversal state starts the traversal.
Example: The Interpreter pattern defines a grammatical representation for a language and an interpreter to interpret the grammar. Musicians are examples of Interpreters. The pitch of a sound and its duration can be represented in musical notation on a staff. This notation provides the language of music [14]. Musicians playing the music from the score are able to reproduce the original pitch and duration of each sound represented.

Iterator: Design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation. An Iterator object encapsulates the internal structure of how the iteration occurs.
How to do it: For example, a tree, linked list, hash table, and an array all need to be iterated with Search, Sort, Next. Rather than having 12 different methods to manage, using this Pattern would allow you to only need to manage 7 methods.
Example: The Iterator provides ways to access elements of an aggregate object sequentially without exposing the underlying structure of the object. On early television sets, a dial was used to change channels. When channel surfing, the viewer was required to move the dial through each channel position, regardless of whether or not that channel had reception. On modern television sets, a next and previous button are used. When the viewer selects the "next" button, the next tuned channel will be displayed. Consider watching television in a hotel room in a strange city. When surfing through channels, the channel number is not important, but the programming is. If the programming on one channel is not of interest, the viewer can request the next channel, without knowing its number.

Mediator: Design pattern that provides a unified interface to a set of interfaces in a subsystem.
Usually a program is made up of a (sometimes large) number of classes. So the logic and computation is distributed among these classes. However, as more classes are developed in a program, especially during maintenance and/or refactoring, the problem of communication between these classes may become more complex.
This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes.
How to do it: Promote looser coupling between these classes by being the only class that has detailed knowledge of the methods of other classes. Classes send messages to the mediator when needed and the Mediator passes them on to any other classes that need to be informed.
Example: The Mediator defines an object that controls how sets of objects interact. Loose coupling between colleague objects is achieved by having colleagues communicate with the Mediator, rather than with each other. The control tower at a controlled airport demonstrates this pattern very well. The pilots of the planes approaching or departing the terminal area communicate with the tower, rather than explicitly communicating with one another. The tower enforces the constraints on who can take off or land. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.


Memento: Design pattern that provides the ability to restore an object to its previous state (undo by rollback).
How to do it: Two objects use the memento pattern: the originator and a caretaker. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To rollback to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker can not, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.
Example: The Memento captures and externalizes an object's internal state, so the object can be restored to that state later. This pattern is common among do-it-yourself mechanics repairing drum brakes on their cars. The drums are removed from both sides, exposing both the right and left brakes. Only one side is disassembled, and the other side serves as a Memento of how the brake parts fit together [8]. Only after the job has been completed on one side is the other side disassembled. When the second side is disassembled, the first side acts as the Memento.

Observer: Design pattern used to observe the state of an object in a program. It is related to the principle of implicit invocation.
How to do it: The essence of this pattern is that one or more objects (called observers or listeners) are registered (or register themselves) to observe an event which may be raised by the observed object (the subject). (The object that may raise an event generally maintains a collection of the observers.)
Example: The Observer defines a one to many relationship, so that when one object changes state, the others are notified and updated automatically. Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and "observes" when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price, which is broadcast to all of the bidders in the form of a new bid.

State: This pattern is used to represent the state of an object. This is a clean way for an object to partially change its type at runtime.
How to do it: Encapsulate the states of an object as discrete objects, each belonging to a separate subclass of an abstract state class.
Example: The State pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.

Strategy: Design pattern that facilitates algorithm selection at runtime.
How to do it: Encapsulate related algorithms in classes that are subclasses of a common superclass. This allows the selection of algorithm to vary by object and also allows it to vary over time.
Example: A Strategy defines a set of algorithms that can be used interchangeably. Modes of transportation to an airport are an example of a Strategy. Several options exist, such as driving one's own car, taking a taxi, an airport shuttle, a city bus, or a limousine service. For some airports, subways and helicopters are also available as a mode of transportation to the airport. Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based on tradeoffs between cost, convenience, and time.

Template method: The template method is used to do the following:
1. Let subclasses implement behavior that can vary.
2. Avoid duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses.
3. To control at which point(s) subclassing is allowed.
The control structure (inversion of control) that is the result of the application of a template pattern is often referred to as the Hollywood Principle: "Don't call us, we'll call you." Using this principle, the template method in a parent class controls the overall process by calling subclass methods as required.
How to do it: Write an abstract class that contains only part of the logic needed to accomplish its purpose. Organize the class so that its concrete methods call an abstract method where the missing logic would have appeared. Provide the missing logic in subclass’ methods that override the abstract methods.
Example: The Template Method defines a skeleton of an algorithm in an operation, and defers some steps to subclasses. Homebuilders use the Template Method when developing a new subdivision. A typical subdivision consists of a limited number of floor plans, with different variations available for each floor plan. Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the latter stages of construction to produce a wider variety of models.

Visitor: Design pattern that allows you to apply different operations to a collection of objects, centralize the operations, and reduce coupling.
How to do it: Implement an operation that involves objects in a complex structure is to provide logic in each of their classes to support the operation. The Visitor pattern provides an alternative way to implement such operations that avoids complicating the classes of the objects in the structure by putting all of the necessary logic in a separate visitor class. The Visitor pattern also allows the logic to be varied by using different visitor classes.
Example: The Visitor pattern represents an operation to be performed on the elements of an object structure, without changing the classes on which it operates. This pattern can be observed in the operation of a taxi company. When a person calls a taxi company he or she becomes part of the company's list of customers. The company then dispatches a cab to the customer (accepting a visitor). Upon entering the taxi, or Visitor, the customer is no longer in control of his or her own transportation, the taxi (driver) is.

Links to this Page