CSE 403 Design Patterns Singleton Memento Flyweight Factory

  • Slides: 54
Download presentation
CSE 403 Design Patterns: Singleton, Memento, Flyweight, Factory, Command Reading: Simply Singleton and Make

CSE 403 Design Patterns: Singleton, Memento, Flyweight, Factory, Command Reading: Simply Singleton and Make Your Apps Fly (R. Geary) 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

Pattern: Singleton a class that has only one instance 2

Pattern: Singleton a class that has only one instance 2

Restricting object creation n Problem: Sometimes we will really only ever need one instance

Restricting object creation n Problem: Sometimes we will really only ever need one instance of a particular class. n n n examples: keyboard reader, bank data collection We'd like to make it illegal to have more than one. Why we care: n n n Creating lots of objects can take a lot of time. Extra objects take up memory. It is a pain to deal with different objects floating around if they are essentially the same. 3

Singleton pattern n singleton: an object that is the only object of its type

Singleton pattern n singleton: an object that is the only object of its type n n n ensures that a class has at most one instance provides a global access point to that instance takes responsibility of managing that instance away from the programmer (illegal to construct more instances) provide accessor method that allows users to see the (one and only) instance possibly the most known / popular design pattern! (this should tell you something) 4

Restricting objects, continued n n One way to avoid creating objects: use static methods

Restricting objects, continued n n One way to avoid creating objects: use static methods instead n Math, System, JOption. Pane n is this a good alternative choice? Why or why not? Problem: lacks flexibility n n Example: static methods can't be passed as an argument to a method, nor returned Problem: cannot be extended n Example: static methods can't be subclassed and overridden like a singleton's could be 5

Implementing Singleton n make constructor(s) private so that they can not be called from

Implementing Singleton n make constructor(s) private so that they can not be called from outside declare a single static private instance of the class write a public get. Instance() or similar method that allows access to the single instance n possibly protect / synchronize this method to ensure that it will work in a multi-threaded program 6

Singleton sequence diagram 7

Singleton sequence diagram 7

Singleton example n consider a singleton class Random. Generator that generates random numbers public

Singleton example n consider a singleton class Random. Generator that generates random numbers public class Random. Generator { private static Random. Generator gen = new Random. Generator(); public static Random. Generator get. Instance() { return gen; } private Random. Generator() {}. . . } n possible problem: always creates the instance, even if it isn't used 8

Singleton example 2 n variation: don't create the instance until needed // Generates random

Singleton example 2 n variation: don't create the instance until needed // Generates random numbers. public class Random. Generator { private static Random. Generator gen = null; public static Random. Generator get. Instance() { if (gen == null) { gen = new Random. Generator(); } return gen; } } n . . . What could go wrong with this version? 9

Singleton example 3 n variation: solve concurrency issue by locking // Generates random numbers.

Singleton example 3 n variation: solve concurrency issue by locking // Generates random numbers. public class Random. Generator { private static Random. Generator gen = null; public static synchronized Random. Generator get. Instance() { if (gen == null) { gen = new Random. Generator(); } return gen; } } n . . . Is anything wrong with this version? 10

Singleton example 4 n variation: solve concurrency issue without unnecessary locking // Generates random

Singleton example 4 n variation: solve concurrency issue without unnecessary locking // Generates random numbers. public class Random. Generator { private static Random. Generator gen = null; } public static Random. Generator get. Instance() { if (gen == null) { synchronized (Random. Generator. class) { // must test again -- can you see why? // sometimes called test-and-set (TTS) if (gen == null) { gen = new Random. Generator(); } } } return gen; } 11

Singleton exercise n n Let's make our game model a singleton. What other classes

Singleton exercise n n Let's make our game model a singleton. What other classes can be singletons in this system? Open issue: What happens if we want a saveable game, where the game state can be stored onto the disk? n Will there be any issues with this that are unique to a singleton class? 12

Pattern: Memento a memory snapshot of an object's state 13

Pattern: Memento a memory snapshot of an object's state 13

Memento pattern n n problem: sometimes we want to hold onto a version of

Memento pattern n n problem: sometimes we want to hold onto a version of an important object's state at a particular moment memento: a saved "snapshot" of the state of an object or objects for possible later use; useful for: n n writing an Undo / Redo operation ensuring consistent state in a network persistency; save / load state between executions of program we'll examine Memento in the context of saving an object to disk using streams 14

I/O streams, briefly n n n stream: an abstraction of a source or target

I/O streams, briefly n n n stream: an abstraction of a source or target of data bytes "flow" to (output) and from (input) streams can represent many data sources: n n files on hard disk another computer on network web page input device (keyboard, mouse, etc. ) 15

Stream hierarchy java. io. Input. Stream Audio. Input. Stream File. Input. Stream Object. Input.

Stream hierarchy java. io. Input. Stream Audio. Input. Stream File. Input. Stream Object. Input. Stream java. io. Output. Stream Byte. Array. Output. Stream File. Output. Stream Object. Output. Stream 16

Serialization n serialization: reading / writing objects and their exact state using I/O streams

Serialization n serialization: reading / writing objects and their exact state using I/O streams n n n allows objects themselves to be written to files, across network, to internet, etc. lets you save your objects to disk and restore later avoids converting object's state into arbitrary text format 17

Classes used for serialization in java. io package: n Object. Output. Stream class represents

Classes used for serialization in java. io package: n Object. Output. Stream class represents a connection to which an object can be written / sent (saved) public class Object. Output. Stream public Object. Output. Stream(Output. Stream out) public void write. Object(Object o) throws IOException n Object. Input. Stream class represents a connection from which an object can be read / received (loaded) public class Object. Input. Stream public Object. Input. Stream(Input. Stream in) public Object read. Object() throws Exception n File. Input. Stream, File. Output. Stream can be constructed from a file name string 18

Serialization example n recommendation: use a memento class that has save/load code // write

Serialization example n recommendation: use a memento class that has save/load code // write the object named some. Object to file "file. dat" try { Output. Stream os = new File. Output. Stream("file. dat"); Object. Output. Stream oos = new Object. Output. Stream(os); oos. write. Object(some. Object); os. close(); } catch (IOException e) {. . . } // load the object named some. Object from file "file. dat" try { Input. Stream is = new File. Input. Stream("file. dat"); Object. Input. Stream ois = new Object. Input. Stream(is); Whatever. Type some. Object = (Whatever. Type) ois. read. Object(); is. close(); } catch (Exception e) {. . . } 19

Memento sequence diagram 20

Memento sequence diagram 20

Making your classes serializable n You must implement the (methodless) java. io. Serializable interface

Making your classes serializable n You must implement the (methodless) java. io. Serializable interface for your class to be compatible with object input/output streams. public class Bank. Account implements Serializable {. . . n ensure that all instance variables inside your class are either serializable or declared transient n transient fields won't be saved when object is serialized 21

serial. Version. UID n There is a versioning issue with serializing and deserializing objects.

serial. Version. UID n There is a versioning issue with serializing and deserializing objects. n n You might save a Bank. Account object, then edit and recompile the class, and later try to load the (now obsolete) object Serializable objects should have a field inside named serial. Version. UID that marks the "version" of the code n (you can set it to 0 and never change it, if you don't need to support multiple versions of the same product) public class Bank. Account implements Serializable { private static final long serial. Version. UID = 0; . . . 22

Back to singleton. . . n Let's make our (singleton) game model serializable n

Back to singleton. . . n Let's make our (singleton) game model serializable n What can happen if a singleton is saved and loaded? n n Is it possible to have more than one instance of the singleton's type in our system? Does this violate the Singleton pattern? Will it break our code? If so, how can we fix it? 23

Singleton example 5 n variation: has strict checks to make sure that we have

Singleton example 5 n variation: has strict checks to make sure that we have not saved a stale reference to the singleton object // Generates random numbers. public class Random. Generator { private static Random. Generator gen = null; . . . public double next. Number() { // put code like this in methods that use/modify it if (this != gen) { throw new Illegal. State. Exception("not singleton"); } } } n n return Math. random(); Is this a good solution? What do we do if we want to save/load a singleton object? 24

Pattern: Flyweight a class that has only one instance for each unique state 25

Pattern: Flyweight a class that has only one instance for each unique state 25

Problem of redundant objects n problem: redundant objects can bog down system n n

Problem of redundant objects n problem: redundant objects can bog down system n n many objects have same state intrinsic vs. extrinsic state n n example: File objects that represent the same file on disk n n new new. . . new File("mobydick. txt") File("notes. txt") 26

Flyweight pattern n flyweight: an assurance that no more than one instance of a

Flyweight pattern n flyweight: an assurance that no more than one instance of a class will have identical state n n n achieved by caching identical instances of objects to reduce object construction similar to singleton, but has many instances, one for each unique-state object useful for cases when there are many instances of a type but many are the same can be used in conjunction with Factory pattern to create a very efficient object-builder examples in Java: String, Image / Toolkit, Formatter 27

Flyweight and Strings n Flyweighted strings n n Java Strings are flyweighted by the

Flyweight and Strings n Flyweighted strings n n Java Strings are flyweighted by the compiler in many cases can be flyweighted at runtime with the intern method String fly = "fly", String fly 2 = "fly", n weight = "weight"; weight 2 = "weight"; Which of the following expressions are true? fly == fly 2 weight == weight 2 "fly" + "weight" == "flyweight" fly + weight == "flyweight" String flyweight = new String("fly" + "weight"); flyweight == "flyweight" String interned = (fly + weight). intern(); interned == "flyweight" 28

Implementing a Flyweight n flyweighting works best on immutable objects n immutable: cannot be

Implementing a Flyweight n flyweighting works best on immutable objects n immutable: cannot be changed once constructed class pseudo-code sketch: public class Flyweighted { n n n static collection of instances private constructor static method to get an instance: n n if (we have created this kind of instance before), get it from the collection and return it else, create a new instance, store it in the collection and return it } 29

Flyweight sequence diagram 30

Flyweight sequence diagram 30

Implementing a Flyweight public class Flyweighted { private static Map instances; private Flyweighted() {}

Implementing a Flyweight public class Flyweighted { private static Map instances; private Flyweighted() {} public static synchronized Flyweighted get. Instance(Object key) { if (!my. Instances. contains(key)) { Flyweighted fw = new Flyweighted(key); instances. put(key, fw); return fw; } else { return instances. get(key); } } } 31

Class before flyweighting n A class to be flyweighted public class Point { private

Class before flyweighting n A class to be flyweighted public class Point { private int x, y; public Point(int x, int y) { this. x = x; this. y = y; } public int get. X() { return x; } public int get. Y() { return y; } public String to. String() { return "(" + x + ", " + y + ")"; } } 32

Class after flyweighting n A class that has been flyweighted! public class Point {

Class after flyweighting n A class that has been flyweighted! public class Point { private static Map<String, Point> instances = new Hash. Map<String, Point>(); public static Point get. Instance(int x, int y) { String key = x + ", " + y; if (instances. contains. Key(key)) { // re-use existing pt return instances. get(key); } } Point p = new Point(x, y); instances. put(key, p); return p; private final int x, y; // immutable private Point(int x, int y) {. . . 33

References n The Java Tutorial: I/O n n Java API pages n n n

References n The Java Tutorial: I/O n n Java API pages n n n http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/io/Object. Input. Stream. html http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/io/Object. Output. Stream. html http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/awt/File. Input. Stream. html http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/awt/File. Output. Stream. html Cunningham & Cunningham OO Consultancy, Inc. n n http: //java. sun. com/docs/books/tutorial/essential/io/ http: //c 2. com/cgi/wiki? Singleton. Pattern http: //c 2. com/cgi/wiki? Memento. Pattern http: //c 2. com/cgi/wiki? Flyweight. Pattern Design Patterns Java Companion n http: //www. patterndepot. com/put/8/Java. Patterns. htm 34

Pattern: Factory (a variation of Factory Method, Abstract Factory) a class or method used

Pattern: Factory (a variation of Factory Method, Abstract Factory) a class or method used to create objects easily 35

Problem: Bulky GUI code n GUI code to construct many components quickly becomes redundant

Problem: Bulky GUI code n GUI code to construct many components quickly becomes redundant (here, with menus): homestar. Item = new JMenu. Item("Homestar Runner"); homestar. Item. add. Action. Listener(this); view. Menu. add(homestar. Item); crap. Item = new JMenu. Item("Crappy"); crap. Item. add. Action. Listener(this); view. Menu. add(crap. Item); n another example (with buttons): button 1 = new JButton(); button 1. add. Action. Listener(this); button 1. set. Border. Painted(false); button 2 = new JButton(); button 2. add. Action. Listener(this); button 2. set. Border. Painted(false); 36

Factory pattern n factory: A class whose job is to easily create and return

Factory pattern n factory: A class whose job is to easily create and return instances of other classes. n n a creational pattern; makes it easier to construct complex objects instead of calling a constructor, use a static method in a "factory" class to set up the object saves lines, complexity to quickly construct / initialize objects examples in Java: borders (Border. Factory), key strokes (Key. Stroke), network connections (Socket. Factory) 37

Using factories in Java n Setting borders on buttons and panels: n use Border.

Using factories in Java n Setting borders on buttons and panels: n use Border. Factory class my. Button. set. Border( Border. Factory. create. Raised. Bevel. Border()); n Setting hot-key "accelerators" on menus: n use Key. Stroke class menu. Item. set. Accelerator( Key. Stroke. get. Key. Stroke('T', Key. Event. ALT_MASK)); 38

Factory implementation When implementing a factory of your own: n The factory itself should

Factory implementation When implementing a factory of your own: n The factory itself should not be instantiated. n n n The factory uses static methods to construct components. The factory should offer as simple an interface to client code as possible. n n make constructor private Don't demand lots of arguments; possibly overload factory methods to handle special cases that need more arguments. Factories are often designed for reuse on a later project or for general use throughout your system. 39

Factory sequence diagram 40

Factory sequence diagram 40

Factory example public class Button. Factory { private Button. Factory() {} public static JButton

Factory example public class Button. Factory { private Button. Factory() {} public static JButton create. Button( String text, Action. Listener listener, Container panel) { JButton button = new JButton(text); button. set. Mnemonic(text. char. At(0)); button. add. Action. Listener(listener); panel. add(button); return button; } } 41

Go. F's variations on Factory Method pattern: A factory object that can be constructed

Go. F's variations on Factory Method pattern: A factory object that can be constructed and has an overridable method to create its objects n n can be subclassed to make new kinds of factories Abstract Factory pattern: When the topmost factory class and its creational method are abstract (can be overridden) 42

Pattern: Command objects that represent actions 43

Pattern: Command objects that represent actions 43

Open-closed principle n n Open-Closed Principle: Software entities like classes, modules and functions should

Open-closed principle n n Open-Closed Principle: Software entities like classes, modules and functions should be open for extension but closed for modifications. The Open-Closed Principle encourages software developers to design and write code in a fashion that adding new functionality would involve minimal changes to existing code. n n Most changes will be handled as new methods and new classes. Designs following this principle would result in resilient code which does not break on addition of new functionality. 44

Command pattern n command: An object that represents an action. n n Sometimes called

Command pattern n command: An object that represents an action. n n Sometimes called a "functor" to represent an object whose sole goal is to encapsulate one function Java API examples: n Action. Listener, Comparator, Runnable / Thread 45

Command applications n Command objects serve as a "model" of commands: n n separates

Command applications n Command objects serve as a "model" of commands: n n separates the user interface from them each model can support multiple views each action can support multiple widgets Use the Command pattern when you want to: n n implement a callback function capability have several UI widgets that cause the same action to occur specify, queue, and execute requests at different times support undo and change log operations 46

Example: Bad event handling public class TTTGui implements Action. Listener {. . . public

Example: Bad event handling public class TTTGui implements Action. Listener {. . . public void action. Performed(Action. Event event) { if (event. get. Source() == view 1 Item){ // switch to view #1. . . else { // event source must be view 2 Item // switch to view #2. . . } n } } in this code, the "master" TTT GUI object is in charge of all action events in the UI n n is this bad? what could happen if we add another action event source? 47

Common UI commands n It is common for a GUI to have several ways

Common UI commands n It is common for a GUI to have several ways to activate the same behavior. n n n Example: toolbar "Cut" button and "Edit / Cut" menu This is good ; it makes the program flexible for the user. We'd like to make sure the code implementing these common commands is not duplicated. 48

Solution: Action objects n Java's Action interface represents a UI command n n n

Solution: Action objects n Java's Action interface represents a UI command n n n a UI command has a text name, an icon, an action to run can define multiple UI widgets that share a common underlying command by attaching the same Action to them These Swing components support Action n n JButton(Action a) JCheck. Box(Action a) JRadio. Button(Action a) JToggle. Button(Action a) JMenu. Item(Action a) Abstract. Action class implements Action and maintains an internal map of keys to values n n n each key represents a name of a property of the action (e. g. "Name") each value represents the value for that property (e. g. "Save Game") can be used to ensure that all UI components that share a common UI action will have the same text, icon, hotkey 49

Action. Listener/Action code n reminder: interface Action. Listener n n public void action. Performed(Action.

Action. Listener/Action code n reminder: interface Action. Listener n n public void action. Performed(Action. Event e) interface Action extends Action. Listener n adds property enabled n n is. Enabled() / set. Enabled(boolean) abstract class Abstract. Action implements Action n you must still write action. Performed 50

Abstract. Action members n public class Abstract. Action implements Action n n n n

Abstract. Action members n public class Abstract. Action implements Action n n n n public public. . . Abstract. Action(String name) Abstract. Action(String name, Icon icon) Object get. Value(String key) boolean is. Enabled() void put. Value(String key, Object value) void set. Enabled(boolean enabled) Abstract. Action object maintains an internal map of keys to values n n Each key represents a name of a property of the action (e. g. "Name"). Each value represents the value for that property (e. g. "Save Game"). 51

Using Action, example n define a class that extends Abstract. Action: public class Cut.

Using Action, example n define a class that extends Abstract. Action: public class Cut. Action extends Abstract. Action { public Cut. Action() { super("Cut", new Image. Icon("cut. gif")); } public void action. Performed(Action. Event e) { // do the action here. . . } } n create an object of this class, attach it to UI objects: Cut. Action cut = new Cut. Action(); JButton cut. Button = new JButton(cut); JMenu. Item cut. Menu. Item = new JMenu. Item(cut); n now the same action will occur in both places; also, changes to the action will be seen on both widgets: cut. set. Enabled(false); 52

Action and Swing n Other uses: properties of the action can be set n

Action and Swing n Other uses: properties of the action can be set n cut. put. Value(Action. SHORT_DESCRIPTION, "Cuts the selected text"); n n cut. put. Value(Action. NAME, "Cut"); n n will use the text label "Cut" for the name of the command cut. put. Value(Action. MNEMONIC_KEY, new Integer('T')); n n will use this label for the tooltip text will underline 't' in "Cut" as a mnemonic hotkey for the command cut. put. Value(Action. ACCELERATOR_KEY, Key. Stroke. get. Key. Stroke('X', Key. Event. CTRL_MASK)); n will use Ctrl-X as an accelerator hotkey for the command 53

References n Java API pages n n n Cunningham & Cunningham OO Consultancy, Inc.

References n Java API pages n n n Cunningham & Cunningham OO Consultancy, Inc. n n http: //c 2. com/cgi/wiki? Abstract. Factory. Pattern http: //c 2. com/cgi/wiki? Factory. Method. Pattern http: //c 2. com/cgi/wiki? Command. Pattern Design Patterns Java Companion n n http: //java. sun. com/j 2 se/1. 5. 0/docs/api/javax/swing/Action. html http: //java. sun. com/j 2 se/1. 5. 0/docs/api/javax/swing/Abstract. Action. html http: //www. patterndepot. com/put/8/Java. Patterns. htm Design Pattern Synopses n http: //www. mindspring. com/~mgrand/pattern_synopses. htm 54