Académique Documents
Professionnel Documents
Culture Documents
Lecture Notes
Design Patterns:
Singleton, Memento, Flyweight
Outline
Singleton pattern
Flyweight pattern
Pattern: Singleton
a class that has only one
instance
why we care:
Singleton pattern
Restricting objects,
continued
Implementing Singleton
Singleton sequence
diagram
Singleton example
Singleton example 2
Singleton example 3
11
Singleton example 4
12
Singleton example
13
Singleton exercise
Pattern: Memento
a memory snapshot of an object's
state
15
Memento pattern
16
Stream hierarchy
java.io.InputStream
AudioInputStream
FileInputStream
ObjectInputStream
java.io.OutputStream
ByteArrayOutputStream
FileOutputStream
ObjectOutputStream
18
Serialization
serialization: reading /
writing objects and their
exact state using I/O streams
Serialization example
21
Memento sequence
diagram
22
Back to singleton...
Singleton example 5
nextNumber() {
like this in methods that use/modify it
gen)
IllegalStateException("not singleton");
return Math.random();
25
Pattern: Flyweight
a class that has only one instance for each
unique state
26
Problem of redundant
objects
problem: existence of redundant objects can
bog down system
new
new
new
...
new
new
File("mobydick.txt")
File("mobydick.txt")
File("mobydick.txt")
File("notes.txt")
File("notes.txt")
27
Flyweight pattern
Flyweighted strings
// true
// true
// true
29
Implementing a Flyweight
30
Flyweight sequence
diagram
31
Implementing a Flyweight
public class Flyweighted {
Map or table of instances
private Flyweighted() {}
public static synchronized Flyweighted getInstance(Object key) {
if (!myInstances.contains(key)) {
Flyweighted fw = new Flyweighted(key);
myInstances.put(key, fw);
return fw;
} else
return (Flyweighted)myInstances.get(key);
}
}
32
A class to be flyweighted
33
// immutable
34
References
http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectInputStream.html
http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectOutputStream.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/FileInputStream.html
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/FileOutputStream.html
http://java.sun.com/docs/books/tutorial/essential/io/
http://c2.com/cgi/wiki?SingletonPattern
http://c2.com/cgi/wiki?MementoPattern
http://c2.com/cgi/wiki?FlyweightPattern
http://www.patterndepot.com/put/8/JavaPatterns.htm
35