C10 Designpatterns
C10 Designpatterns
and Design
Design Patterns and GUI Programming
Reading:
Object-Oriented Design and Patterns, Ch. 5 (Horstmann)
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
designs often emerge from trial and error
successful designs do exist
two designs they are almost never identical
they exhibit some recurring characteristics
Can designs be described, codified or standardized?
this would short circuit the trial and error phase
produce "better" software faster
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
Example:
9
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
10
Pattern: Observer
objects whose state can be watched
11
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
12
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
renderin
Model View
g
View
Component
Model updates events
Controller
Controll
13
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
14
Observer sequence diagram
16
Observer interface
package java.util;
17
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.
18
Common usage of Observer
1. write a model class that extends Observable
have the model notify its observers when anything significant
happens
2. make all views of that model (e.g. GUI panels that draw
the model on screen) into observers
have the panels take action when the model notifies them of
events (e.g. repaint, play sound, show option dialog, etc.)
19
Using multiple views
make an Observable model
20
Example: changing views
model.deleteObserver(view1);
model.addObserver(view2);
view1.setVisible(false);
view2.setVisible(true);
21
Pattern: Strategy
objects that hold alternate algorithms to solve a
problem
22
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
23
Strategy example: Card player
// setting a strategy
player1.setStrategy(new SmartStrategy());
// using a strategy
Card p1move = player1.move(); // uses strategy
24
Containers with layout
The idea: Place many components into a special component called
a container, then add the container to the window frame
25
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.
26
Pattern: Composite:
objects that can serve as containers, and can hold other objects like themselves
Composite pattern is used where we need to treat a group of objects in similar way as a
single object. Composite pattern composes objects in term of a tree structure to
represent part as well as whole hierarchy.
27
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.)
28
Composite example: panels
Container north = new JPanel(new FlowLayout());
north.add(new JButton("Button 1"));
north.add(new JButton("Button 2"));
29
Pattern: Decorator
objects that wrap around other objects to add
useful features
30
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
31
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
32
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
33
References
The Java Tutorial: Visual Index to the Swing Components.
http://java.sun.com/docs/books/tutorial/
uiswing/components/components.html