Title: A Few Design Patterns
1Computing Fundamentals with Java ?Rick
Mercer Franklin, Beedle Associates, 2002 ISBN
1-887902-47-3
A Few Design Patterns A Few Exceptions A Little
Standard IO, and Persistent Objects
2Outline
- Object-Oriented Design Patterns
- Mediator Design Pattern
- Exception Handling
- try and catch blocks
- Standard Java I/O
- Decorator Design Pattern
- Java stream objects
- JScrollPane
- Persistence
- Serialization
- ObjectOutputStream
- ObjectInputStream
3OO Design Patterns
- Design Patterns Elements of Reusable
Object-Oriented Software, Gamma et al., - referred to as the Gang of Four (GoF) book.
- Patterns
- facilitate communication of OO designs (names)
- provide tried and true design solutions
- examples of good OO design accepted by experts
- can be applied in different contexts
4OO Design Patterns
- Patterns reduce discovery costs and design
complexity - A Design Pattern is a solution to a recurring
problem, occurring in different contexts, often
balancing competing forces
5Pattern Names/Examples
- A few patterns some have been mentioned
- Mediator Coordinate activities between other
objects - Composite File system / Menus / JPanels /
Portfolio - Strategy Layout Managers / Decide what cards to
play - Iterator Iterator with next and hasNext
- Decorator Java IO Streams / JScrollPane
6The Mediator Pattern from GoF
- Intent
- Define an object that encapsulates how a set of
objects interact. Mediator promotes loose
coupling by keeping objects from referring to
each other explicitly, and it lets you vary their
interaction independently. - Motivation
- OO design encourages the distribution of behavior
among objects - This results in many connections (associations)
between objects - Worst case Every object knows about each other
- Can't reuse objects as easily
- Can avoid these problems by encapsulating
collective behavior in a separate mediator object
7Mediator
- Mediator
- A Mediator is responsible for controlling and
coordinating the interactions of a group of
objects - The mediator serves as a go-between between other
objects - The mediator knows all objects, but the objects
don't know each other - See non-computer example of Mediator from our web
site
8Examples
- The Disk Jockey (or WebPage or Radio Station)
coordinates activities between several objects - it has relationships with several objects
- The ATM System in C Sc 335 a conceptual model
9Another Example
- CourseScheduler in current project could do the
work of adding and dropping courses - Needs to talk to semester schedule and logged in
student
10Riel's Heuristic 4.13
- A few of Arthur Riel's design heuristics
(guidelines) support this design (use Mediator) - A class must know what it contains, but the
con-tained objects should not know who contains
it - OK for Account to know that it has a String, but
String shouldn't be dependent on Account - Can reuse String in other places
- Student and SemesterSchedule are not dependent on
CourseScheduler
11Riel's Heuristic 4.14
- Objects that share lexical scope--those contained
in the same containment--should not have uses
relationships between them. - Consider an ATM which contains a card reader and
a display screen - The card reader should not send a message to the
display screen - better reuse--could use the card reader at a door
without taking along the display screen
12Violation of the heuristics increases complexity
- An ATM may contain
- card reader, display screen, and keypad
- The ATM should coordinate activities between
these three objects - We dont need to have additional collaborations
Automated Teller Machine
HaveACard?()
displayPIN()
Display
Card Reader
getPIN()
Keypad
13Course Reg System
- CourseScheduler may send messages to Student,
StudentSchedule, SemesterSchedule - These may exist independently
- Example A printer may print any StudentSchedule
or the Semester schedule independently - The SemesterSchedule may be built by a registrar
independently of any StudentSchedule - When add and drop rules change, which class will
need to be modified? Will this make sense in
2004?
14Things still needed for Course Registration
- Persistence objects
- Exception Handling
- Java I/O stream
- WindowListener
15Exceptions
- When programs run, exception events occur a 3rd
thing that is sure in life, besides death and
taxes - Examples of "exceptional events" include
- Division by 0
- Attempt to open and it fails
- Array subscript out of bounds
- Trying to convert a string that is not a number
into a number - Open a file that does not exist
- Handle these with Java's exception handling
16Handling exceptional events
- Put code that "throws" exceptional event into a
try block and add a catch block. - try
-
- code that cause an exceptional event
(throws an exception) -
- catch(Exception anException)
-
- code that executes when the code in
try above throws an exception -
- If the code in the try block causes an
except-ional event, control transfer to the catch
block.
17Example (a repeat)
- ParseDouble may be passed a string that does not
represent a valid number. - String numberAsString depositField.getText()
- double amount 0.0
- try
- // the next message may "throw an exception"
- amount Double.parseDouble(numberAsString)
- System.out.println("This message may not be
sent") -
- catch(NumberFormatException nfe)
-
- JOptionPane.showMessageDialog(null,
- "Not a valid deposit amount"
numberAsString) -
18parseDouble
- public static double parseDouble(String s)
- throws NumberFormatException
- Returns a number new represented by s
- Parameters s - the string to be parsed.
- Returns the double value represented by the
string argument. - Throws NumberFormatException - if the string
does not represent a valid number, 1o0.0 for
example. - Many methods throw an exception
- Your methods could also
19A small piece of Java's large Exception hierarchy
- Code that throws RuntimeException need not be in
a try block, All others must be "tried" (there is
an alternative).
20Input/Output Streams
- Input is read through input stream objects
- Output is written through output stream objects
- A stream is a sequence of items read from some
source or written to some destination - Can do "standard" input (no TextReader)
- Can read text from and write text to files
- Or we can read and write entire objects
- This allows for persistent objects
21Persistent Objects
- A persistent object is one that stays around
after a program terminates - Can be used by other programs, or when the same
program begins again - Entire objects, even very big ones, can be
written to a file on a disk and read from a file
on a disk - Use ObjectOutputStream and its writeObject method
- Use ObjectInputStream and its readObject method
22Write a list to disk
- //Simulate creation of a static (hard coded) list
- list.put("A", new BankAccount("A", 12.34))
- list.put("B", new BankAccount("B", 45.67))
- list.put("C", new BankAccount("C", 200.00))
- // Simulate changes to the objects in the list
- ((BankAccount)list.get("A")).deposit(9999999)
- ((BankAccount)list.get("C")).withdraw(200)
- try
-
- FileOutputStream bytesToDisk
- new FileOutputStream(fileName)
- ObjectOutputStream outFile
- new ObjectOutputStream(bytesToDisk)
- // outFile understands the writeObject message.
- // Make the object persist so it can be read
later. - outFile.writeObject(list)
- outFile.close() // Always close the output
file! -
23Serializable
- The objects must be Serializable
- ArrayList, String and many other Java classes do
this already - The primitive types and arrays are also
persistent - Classes you write will need the Serializable tag
- public class Account // can implement 2 or
more - implements Comparable,
Serializable - The instance variables must also be Serializable
or transient, which means they are not written to
the output stream or read from a stream
24A Serialized Object in Memory
25Read back in
- try
- // Open the stream
- FileInputStream diskToBytes
- new FileInputStream(fileName)
- ObjectInputStream inFile
- new ObjectInputStream(diskToBytes)
- // inFile understands the readObject message.
- // Simulate the program starting again with
saved state. - HashMap localCollection (HashMap)inFile.readOb
ject() - inFile.close() // Always close the output
file! - System.out.println(localCollection.get("A"))
- System.out.println(localCollection.get("B"))
- System.out.println(localCollection.get("C"))
-
- catch( ClassNotFoundException cnfe )
-
- System.out.println( "Wrong class of object "
cnfe ) -
- catch(IOException ioe)
26Multiple catch blocks
- readObject may throw ClassNotFoundException
- One try block may have one to many catch blocks
associated with it
27Decorator Pattern in Java
- InputStreamReader
- ... bridge from byte streams to character
streams It reads bytes and translates them into
characters using the specified character
encoding. JavaTMAPI - BufferedReader
- Read text from a character-input stream,
buffering characters so as to provide for the
efficient reading of characters, arrays, and
lines. JavaTMAPI - What programmer's can now code
- BufferedReader keyboard new BufferedReader(
- new InputStreamReader(System.in))
28Decorator Example
BufferedReader decorates InputStreamReader
BufferedReader readLine()
ready()
InputStreamReader read() close()
29Java streams
- With gt 60 streams in Java, you can create a wide
variety of input and output streams - this provides flexibility good
- it also adds complexity bad
- Flexibility made possible with inheritance and
classes that accept many different classes that
extend the parameter - You can have an InputStream instance or any
instance of a class that extends InputStream - public InputStreamReader(InputStream in)
30One Constructor for many subclasses
- InputStream has these direct known subclasses
ByteArrayInputStream, FileInputStream,
FilterInputStream, InputStream,
ObjectInputStream, PipedInputStream,
SequenceInputStream, StringBufferInputStream - System.in is an instance of InputStream
- Next we will see decorators for persistence
- FileInputStream decorated with ObjectInputStream
to read objects (not text) from a file - FileOutputStream decorated with
ObjectOutputStream to write objects (not text) to
a file
31WindowListener
- Check the API or WindowListener
- WindowClosing is the event you want to handle
- The other 6 methods could be do nothing
- You could extend WindowAdaptor