Lecture10 Patterns
Lecture10 Patterns
Reading:
Object-Oriented Design and Patterns, Ch. 5 (Horstmann)
These lecture slides are copyright (C) Marty Stepp, 2007. They may not be rehosted, sold, or
modified without expressed permission from the author. All rights reserved.
1
Big questions
What is a design pattern?
2
Design challenges
Designing software for reuse is hard. One must find:
a good problem decomposition, and the right software
a design with flexibility, modularity and elegance
3
Design patterns
design pattern:
a solution to a common software problem in a context
describes a recurring software structure
is abstract from programming language
identifies classes and their roles in the solution to a problem
patterns are not code or designs; must be instantiated/applied
4
History of patterns
the concept of a "pattern" was first expressed
in Christopher Alexander's work A Pattern
Language in 1977 (2543 patterns)
5
Benefits of using patterns
patterns are a common design vocabulary
allows engineers to abstract a problem and talk about that
abstraction in isolation from its implementation
embodies a culture; domain-specific patterns increase design
speed
6
Gang of Four (GoF) patterns
Creational Patterns
(abstracting the object-instantiation process)
Factory Method Abstract Factory Singleton
Builder Prototype
Structural Patterns
(how objects/classes can be combined to form larger structures)
Adapter Bridge Composite
Decorator Facade Flyweight
Proxy
Behavioral Patterns
(communication between objects)
Command Interpreter Iterator
Mediator Observer State
Strategy Chain of Responsibility Visitor
Template Method
7
Pattern: Iterator
objects that traverse collections
8
Iterator pattern
iterator: an object that provides a standard way to
examine all elements of any collection
uniform interface for traversing many different data structures
supports concurrent iteration and element removal
9
Pattern: Observer
objects whose state can be watched
10
Recall: model and view
model: classes in your system that are related to the
internal representation of the state of the system
often part of the model is connected to file(s) or database(s)
examples (card game): Card, Deck, Player
examples (bank system): Account, User, UserList
11
Model-view-controller
model-view-controller (MVC): common design
paradigm for graphical systems
controller: classes that connect model and view
defines how user interface reacts to user input (events)
receives messages from view (where events come from)
sends messages to model (tells what data to display)
sometimes part of view (see left)
data for
rendering
Model View
View
Component
Model updates events
Controller
Controller
12
Observer pattern
observer: an object that "watches" the state of
another object and takes action when the state
changes in some way
examples in Java: event listeners; java.util.Observer
13
Benefits of observer
abstract coupling between subject and observer; each
can be extended and reused individually
15
Observer interface
package java.util;
16
Observable class
public void addObserver(Observer o)
public void deleteObserver(Observer o)
Adds/removes o to/from the list of objects that will be notified (via their
update method) when notifyObservers is called.
17
Common usage of Observer
1. write a model class that extends Observable
have the model notify its observers when anything significant
happens
18
Using multiple views
make an Observable model
19
Example: changing views
model.deleteObserver(view1);
model.addObserver(view2);
view1.setVisible(false);
view2.setVisible(true);
20
Pattern: Strategy
objects that hold alternate algorithms to solve a
problem
21
Strategy pattern
strategy: an algorithm separated from the object that
uses it, and encapsulated as its own object
each strategy implements one behavior, one implementation of
how to solve the same problem
separates algorithm for behavior from object that wants to act
allows changing an object's behavior dynamically without
extending / changing the object itself
examples:
file saving/compression
layout managers on GUI containers
AI algorithms for computer game players
22
Strategy example: Card player
// setting a strategy
player1.setStrategy(new SmartStrategy());
// using a strategy
Card p1move = player1.move(); // uses strategy
23
Containers with layout
The idea: Place many components into a special component called
a container, then add the container to the window frame
24
Container
container: an object that holds components; it also
governs their positions, sizes, and resize behavior
public void add(Component comp)
public void add(Component comp, Object info)
Adds a component to the container, possibly giving
extra information about where to place it.
public void remove(Component comp)
Removes the given component from the container.
public void setLayout(LayoutManager mgr)
Uses the given layout manager to position the
components in the container.
public void validate()
You should call this if you change the contents of a
container that is already on the screen, to make it re-
do its layout. 25
Pattern: Composite
objects that can serve as containers, and can hold
other objects like themselves
26
Composite pattern
composite: an object that is either an individual item
or a collection of many items
composite objects can be composed of individual items or of
other composites
recursive definition: objects that can hold themselves
examples in Java:
collections (a List of Lists)
GUI layout (panels containing panels containing buttons, etc.)
27
Composite example: panels
Container north = new JPanel(new FlowLayout());
north.add(new JButton("Button 1"));
north.add(new JButton("Button 2"));
28
Pattern: Decorator
objects that wrap around other objects to add
useful features
29
Decorator pattern
decorator: an object that modifies behavior of, or
adds features to, another object
decorator must maintain the common interface of the object it
wraps up
used so that we can add features to an existing simple object
without needing to disrupt the interface that client code expects
when using the simple object
the object being "decorated" usually does not explicitly know
about the decorator
examples in Java:
multilayered input streams adding useful I/O methods
adding scroll bars to GUI controls
30
Decorator example: I/O
normal InputStream class has only public int
read() method to read one letter at a time
decorators such as BufferedReader or Scanner add
additional functionality to read the stream more easily
31
Decorator example: GUI
normal GUI components don't have scroll bars
JScrollPane is a container with scroll bars to which you
can add any component to make it scrollable
32
References
The Java Tutorial: Visual Index to the Swing Components.
http://java.sun.com/docs/books/tutorial/
uiswing/components/components.html