You are on page 1of 21

Design Patterns

CSc 335
Object-Oriented Programming and Design
Fall 2006
Acknowledgements
• These slides were written by Richard Snodgrass. Some slides from
Rick Mercer and Martin Stepp were used.

• They include information in Design Patterns: Elements of


Reusable Object-Oriented Software, by Erich Gamma, Richard
Helm, Ralph Johnson, and John Vlissides, Addison-Wesley
Publishing Company, 1995.

• Some information was taken from Refactoring: Improving the


Design of Existing Code, by Martin Fowler, Addison-Wesley
Publishing Company, 1999.

• Inspiration was also taken from Head First Design Patterns, by


 Eric Freeman, Elisabeth Freeman, Kathy Sierra, and Bert Bates,
O’Reilly Media, October, 2004.
P-2
Patterns I
Outline

• Overview of Patterns

• Iterator

• Strategy

P-3
Patterns I
The Germ of this Approach
• Christopher Alexander, architect
 A Pattern Language---Towns, Buildings, Construction
(1977)
 Timeless Way of Building (1979)
 “Each pattern describes a problem which occurs over and
over again in our environment, and then describes the core of
the solution to that problem, in such a way that you can use
this solution a million times over, without ever doing it the
same way twice.”

• Other patterns: novels (tragic, romantic, crime),


movies, bureaucratic memos, political speeches…

P-4
Patterns I
“Gang of Four” (GoF) Book
• Design Patterns: Elements of Reusable Object-
Oriented Software, Addison-Wesley Publishing
Company, 1994.
 Dr. Erich Gamma, then Software Engineer, Taligent, Inc.;
now at Object Technology International as the technical
director of the Zurich lab in Switzerland.
 Dr. Richard Helm, then Senior Technology Consultant, DMR
Group; now at the Boston Consulting Group.
 Dr. Ralph Johnson, then and now at University of Illinois,
Computer Science Department; now a Research Associate
Professor.
 Dr. John Vlissides, then a researcher at IBM Thomas J.
Watson Research Center.
P-5
Patterns I
Patterns
• This book defined 23 patterns, classified into three
categories.
 Creational patterns, which deal with the process of object
creation.
 Structural patterns, which deal primarily with the static
composition and structure of classes and objects.
 Behavioral patterns, which deal primarily with dynamic
interaction among classes and objects.
• Many other patterns have been introduced by others.
 For example, the book Data Access Patterns by Clifton
Nock introduces 4 decoupling patterns, 5 resource patterns, 5
I/O patterns, 7 cache patterns, and 4 concurrency patterns.
 Hundreds of patterns have been documented since; other
examples include telecommunications patterns, pedagogical
patterns, analysis patterns, and indexing patterns.
P-6
Patterns I
GoF Patterns
• Creational Patterns • Behavioral Patterns
 Abstract Factory  Chain of Responsibility
 Builder  Command
 Factory Method  Interpreter
 Prototype  Iterator
 Singleton  Mediator
• Structural Patterns  Memento
 Adapter  Observer
 Bridge  State
 Composite  Strategy
 Decorator  Template Method
 Façade  Visitor
 Flyweight
 Proxy

P-7
Patterns I
Why Study Patterns?
• Can reuse solutions.
 Gives us a head start
 Avoids the gotchas later (unanticipated things)
 No need to reinvent the wheel

• Establish common terminology


 Design patterns provide a common point of reference
 Easier to say, “We need some Strategies here.”

• Provide a higher level prospective.


 Frees us from dealing with the details too early.
P-8
Patterns I
A Common Style for Patterns

• Formats of pattern writers vary, but a pattern


description usually has at least these four things.
 A name
 The purpose of the pattern, the problem it solves
 A guide for how to accomplish the solution
 The constraints and forces to be considered in order to
accomplish the solution

P-9
Patterns I
Style for Describing Patterns
• We will use this structure in these slides.
• Pattern name
• Recurring problem: what problem the pattern addresses
• Solution: the general approach of the pattern
• Also known as: other names for the pattern
• UML for the pattern
• Participants: a description of the classes in the UML
• Explanation
• Use Example(s): examples of this pattern, in Java
• Variant(s): different refinements of this pattern

P-10
Patterns I
Outline
• Overview of Patterns

• Iterator

• Strategy

P-11
Patterns I
Iterator Pattern
• Recurring Problem:
 You have an aggregate data type. How can you access the
elements sequentially without exposing its underlying
representation?

• Solution:
 Provide a separate object, an iterator, that can retain the
current position, and go to the next element.

• Also known as:


 Cursor

P-12
Patterns I
Use Example: Collections Framework
• The Collections framework has an Iterator
interface.
 boolean hasNext() Is the iterator positioned at the last
element in the aggregate?
 Object next() Move to the next element and return it.
 void remove() Remove the object most recently
returned by next().
• The remove() method is optional. If an Iterator
does not support this method, it throws
java.lang.UnsupportedOperationException
when invoked.
• Collection has the method
Iterator Iterator()
P-13
Patterns I
Use Example, cont.
• An Iterator can be used to look through the elements of any
kind of collection (as an alternative to a for loop).

Song song1 = new Song("Cheryl Crowe", "Home", 124, "Home.mid");


Song song2 = new Song("Sting", "Fields of Gold", 212, "gold.mp3");
Song song3 = new Song("Beatles", "Help", 132, "Help.mid");

Collection<Song> allSongs = new TreeSet<Song>();


allSongs.add(song1); TreeSet could be ArrayList, LinkedList
allSongs.add(song2);
allSongs.add(song3);

// Iterate over all elements


Iterator<Song> itr = allSongs.iterator();
while (itr.hasNext()) {
Song s = itr.next();
System.out.println(s.getArtist());
}

P-14
Patterns I
Strategy Pattern
• Recurring Problem:
 We want to be able to switch strategies

• Solution:
 Define a strategy as an interface, then instantiate multiple
strategies as concrete classes

• Also known as:


 Policy

P-15
Patterns I
Participants
• Context
 Maintains a reference to a Strategy object.
 Example: The content pane of a JFrame has a layout strategy that can be
changed

• Strategy
 Declares an interface common to all supported algorithms:
AlgorithmInterface.
 Example interface LayoutManager that defines methods that to place
components

• ConcreteStrategy
 Implements the Algorithm interface.
 Example: BorderLayout, GridLayout, FlowLayout, ...

P-16
Patterns I
Layout Managers
• There are five predefined layout managers in the
javax.swing package:

flow layout

border layout

card layout

grid layout

grid bag layout
• Each container has a default layout manager
• You can also create you own custom layout managers
but not necessary here

P-17
Patterns I
A Layout Manager

• By default, JFrame uses BorderLayout


getContentPane().setLayout(new FlowLayout());

• Then when you add, things are added laid out


according to the layout strategy

P-18
Patterns I
Flow Layout
• Components are placed in a row from left to right
in the order in which they are added
• A new row is started when no more components
can fit in the current row
• Components are centered in each row

P-19
Patterns I
Example of FlowLayout in a JFrame
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

public class FrameWithFlowLayout extends JFrame {


public static void main(String[] args) {
new FrameWithFlowLayout().setVisible(true);
}

public FrameWithFlowLayout() {
setSize(200, 160);
Container contentPane = this.getContentPane();
// Without changing layout manager, all buttons go to Center
contentPane.setLayout(new FlowLayout());
contentPane.add(new JButton("1"));
contentPane.add(new JButton("2"));
contentPane.add(new JButton("3"));
contentPane.add(new JButton("4"));
contentPane.add(new JButton("5"));
contentPane.add(new JButton("6"));
contentPane.add(new JButton("7"));
contentPane.add(new JButton("8"));
contentPane.add(new JButton("9"));
}
}

P-20
Patterns I
Grid Layout
• Components are placed in a grid with a user-specified
number of columns and rows
• Each component occupies exactly one grid cell
• Grid cells are filled left to right and top to bottom
• All cells in the grid are the same size
• Change the strategy like this to see the different
arrangement
contentPane.setLayout(new GridLayout(3, 3));

P-21
Patterns I

You might also like