Académique Documents
Professionnel Documents
Culture Documents
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
Design challenges
Design patterns
History of patterns
Creational Patterns
Factory Method
Builder
Abstract Factory
Prototype
Singleton
Structural Patterns
Adapter
Decorator
Proxy
Bridge
Facade
Composite
Flyweight
Behavioral Patterns
Command
Mediator
Strategy
Template Method
Interpreter
Observer
Chain of Responsibility
Iterator
State
Visitor
Pattern: Iterator
objects that traverse collections
Iterator pattern
10
Iterators in Java
map.keySet().iterator()
map.values().iterator()
11
preferred:
public class PlayerList {
public Iterator<Player> iterator() { ... }
public int size() { ... }
public boolean isEmpty() { ... }
}
12
Pattern: Observer
objects whose state can be watched
13
14
Model-view-controller
Model
View
Component
data for
renderin
g
events
updates
Model
View
Controller
Controll
15
Observer pattern
16
Benefits of observer
18
Observer interface
package java.util;
public interface Observer {
public void update(Observable o, Object arg);
}
19
Observable class
20
have the panels take action when the model notifies them of
events (e.g. repaint, play sound, show option dialog, etc.)
21
give each its own unique inner components and code to draw
the model's state in its own way
22
23
Pattern: Strategy
objects that hold alternate algorithms to solve a
problem
24
Strategy pattern
examples:
file saving/compression
layout managers on GUI containers
AI algorithms for computer game players
25
// uses strategy
26
27
28
Container
container: an object that holds components; it also
governs their positions, sizes, and resize behavior
JPanel
A panel is our container of choice; it is a subclass of
Container, so it inherits the methods from the previous
slide and defines these additional methods (among
others):
public JPanel()
Constructs a panel with a default flow layout.
30
31
BorderLayout
public BorderLayout()
32
FlowLayout
public FlowLayout()
33
GridLayout
public GridLayout(int rows, int columns)
34
BoxLayout
Box.createHorizontalBox()
Box.createVerticalBox()
35
Other layouts
CardLayout
layers of "cards" stacked
on top of each other;
one visible at a time
GridBagLayout
very complicated;
my recommendation:
never ever use it
36
37
38
Pattern: Composite
objects that can serve as containers, and can hold
other objects like themselves
39
Composite pattern
<node>
::= <leafnode> | <compositenode>
<compositenode> ::= <node>*
examples in Java:
40
41
Pattern: Decorator
objects that wrap around other objects to add
useful features
42
Decorator pattern
examples in Java:
43
44
45
References
http://c2.com/cgi/wiki?IteratorPattern
http://c2.com/cgi/wiki?DecoratorPattern
http://c2.com/cgi/wiki?CompositePattern
http://www.patterndepot.com/put/8/JavaPatterns.htm
46