Transcript Slide 1

Object Oriented Programming
Lecture IV
Design Patterns, The Observer Observable
Pattern, Some notes on Enumeration Types, I/O
Streams and Exceptions
1
Short Recapitulation of
Last Lecture
• We talked about
– Inheritance and reusal
• A few different aspects on reusability
• Overriding vs. Overloading
–
–
–
–
Interfaces
Abstract classes
Polymorphism
Packages
• Also usable for name (Class) collision
2
Today
• What is a design pattern?
• A first design pattern
– Observer Observable
• Throwables and Exceptions
• Type Enumeration
3
Design Pattern - What is it?
• A design pattern is a descriptive solution that
can be used systematically to solve a recurring
problem
– Can be applied in many engineering disciplines
• Why are design patterns useful?
– 1. A number of patterns that can be used as
guidance, during the design phase of a program
– 2. Reusage of proved solutions, for fast and reliable
software development
– 3. A common vocabulary to simplify communication
between designers.
4
The Pen Object Example
What functionality do we want when using a pen(interface)?
Constructor
pen()
Methods for changing the state of a pen(instance methods)
void lift()
void push()
void move(double d)
void turn(double alpha)
Methods for assigning a drawing area to our pen
void setPaper(Paper p)
5
Pen is a Mutable Object
Pen thePen;
...
public void recLine(int n, double length){
if (n==0)
thePen.move(length);
else{
int m = n-1;
double shorter = length/3.0;
double alpha = Math.PI/3;
recLine(m,shorter);
thePen.turn(-alpha);
recLine(m,shorter);
thePen.turn(2*alpha);
recLine(m,shorter);
thePen.turn(-alpha);
recLine(m,shorter);
}
}
Modifies the state
of the pen itself.
Pen is mutable
6
Let’s take a look at
move(double d)
public void move(double d){
double oldx = x;
double oldy = y;
x = Math.min(x+d*Math.cos(alpha),paper.width());
y = Math.min(y+d*Math.sin(alpha),paper.height());
if(down)
paper.drawLine((int)oldx,(int)oldy,(int)x,(int)y);
}
7
Our first design pattern:
Observer-Observable
• Now, let’s examine the properties of a
Paper
width
height
Canvas is
an AWT
component
A paper is a Canvas
that has height and
width dimensions in
pixels. It also has a
paint method to
show the lines
drawn by the Pen.
8
Observer – Observable
Separation of Model and View
• Paper (Model)
– Add a new line
– Width
– Height
– Add Observer
– Register changes
– Notify the Observers
• Paperview (View)
– Override the paint
method so that it
paints the state of the
model (lines)
– Define the method
update so a change
in the model will be
reflected in the view
9
Extending Observable
• The Observable class implements methods for
attaching to, and interacting with a set of
Observers
– method to add Observers to the Set
– method to notify Observers of changes by calling the
Observers update method
• By extending Paper with Observable, we will
inherit this mechanism and gain access to
necessary methods
• We only need to know which are the Observers
10
The Paper Class:
Observable
public class Paper extends Observable{
private Vector lines;
private int width, height;
…
public Paper(int width, int height){
this.width = width;
this.height = height;
lines = new Vector();
}
public void drawLine(int a, int b, int c, int d){
We have added a
lines.add(new Line(a,b,c,d));
line...
setChanged();
Register the change in
notifyObservers();
Observer!
}
Notify the Observers!
...
11
The PaperView Class
public class PaperView extends Canvas implements Observer{
private Paper paperModel;
public PaperView(Paper p){
paperModel = p;
paperModel.addObserver(this);
…
}
public void update(Observable o, Object arg){
try{Thread.sleep(200);}catch(Exception e){}
repaint();
}
public void paint(Graphics g){
Iterator iter = paperModel.iterator();
while(iter.hasNext()){
Line line = (Line)iter.next();
g.drawLine(line.v, line.w, line.x, line.y);
}
}
Called when
notifying observers!
How we paint the lines!
}
12
A few things about Throwables
& Exceptions
• Exceptions are/should be generated when
unexpected or faulty conditions occur in a
program
• When a fault occurs, an exception can be
thrown and the normal program flow is
interrupted
• There are three kinds of Throwables:
–
–
–
Error (severe)
RuntimeException (for example ”array out of bounds”)
Exception (User defined exception should extend this)
13
Exceptions
Serious Fault!
OutOfMemoryError
Thrown By JVM!
Error
AssertionError
Throwable
ArithmeticException
ClassCastException
RuntimeException
IndexOutOfBoundsException
NullpointerException
Exception
Io-Exception
Any program!
14
Catching Exceptions
Exceptions are caught & handled with a ”try-catchclause”:
Try{
a = b[i];
}catch (ArrayOutOfBoundsException e){
”exception handling code here...”
}finally{...clean up before leaving} (...finally is not necessary)
User defined exceptions must extend class Exception:
MyVeryOwnException extends Exception{
super(”A terrible error has occured!”);
}
15
Throwing Exceptions
•
•
Most Exceptions are thrown by the JVM
But Exceptions can also be thrown anywhere in a
program:
Public int example(void) throws MyException{
”method code...”
throw new MyException();
}
•
•
Method calls to methods that has a throws
statement must be encapsulated with ”try-catch”
clause
The exception should be handled in ”catch” or be
thrown to the object that was calling the method.
16
The Java I/O Framework
•
•
The I/O framework is designed with intention to be
flexible and easy to configure
Java has two main types of I/O:
–
Stream IO
•
•
–
Random Access I/O
•
•
•
Supports reading/writing sequentially
A stream can only be open for read or write, not both
Reading and writing at any position in a file
File I/O can be open both for read/write
Two kinds of streams
–
bytes or character streams
17
I/O Byte Streams
•
The basic I/O streams are:
–
Input Stream
•
•
•
•
•
–
read();
read(byte[] a);
read(byte[] a, int off, int len);
skip(long n);
close();
- reads byte
- reads byte array
- reads part of byte array
- skips over n bytes
- closes the stream
OutputStream
•
•
•
•
write(b);
write(byte[] a);
write(byte[] a, int off, int len);
close();
- writes byte
- writes byte array
- writes part of byte array
- closes the stream
18
Reading from files
• FileInputStream and FileOutputstream are sub
classes of Input and OutputStream byte
streams (overloads methods)
• Byte streams are hardly convenient to use
directly, requires very ”low-level manipulation”
– bitmasking and type conversion
• This kind of ”low-level” streams are rarely
necessary
– most data are represented by Objects
19
Buffered Streams
• BufferedInputStream and
BufferedOutputStream (extends
java.io.FilterInputStream)
– reads data via an ”internal” buffer (JVM managed)
• BufferedReader and BufferedWriter (extends
java.io.Reader)
– abstract streams that we can use for reading
string/character data
– can be used to read entire Strings
20
Object serialization
• Java supports object serialization
– objects can be passed as arguments to a stream
– the objects are ”transparently” serialized to a
sequence of bytes
• Objects must implement the Serializable
interface (java.io.Serializable)
• ObjectInputStream and ObjectOutPutStream
– FileInputStream/FileOutPutStream as arguments for
file reading
21
Enumeration Types
• Enumeration types, what is it?
– it is a finite set of distinct user defined values
• Example of Enumerated types:
– Date = Mon|Tue|Wed|Thu|Fri|Sat|sun
– Direction = North|East|South|West
• We can use the Enumerated types like any
other type in our program
– Ex. Date d = Monday;
• The Enumerated types should be type safe
22
Enumerated types
•
•
Some languages like C/C++ support enumerated types...
In C or C++, we would write:
enum Date {Mon,Tue,Wed,Thu,Fri,Sat,Sun};
Date day1 = Tue;
Date day2 = Fri;
If(day1 == day2){....}
•
•
Untill Java 1.5 was released, Java didn’t support typesafe
enumeration types
Before 1.5 a common (but bad) solution: Treat enumeration
types as static int constants.
23
A Type safe Idiom
• Type safe enumeration idiom
– each value will be distinct (unique)
– a printable, descriptive name rather that just an
Integer number
• Let’s look at an example
– an ”unordered” Type-Safe Enumeration
• In the book, you can also find
– an ”ordered” Type-Safe Enumeration
24
Typesafe enumeration is
supported in Java 1.5
Public class Card{
public enum Rank { Deuce, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace}
public enum Suit{ Clubs, Diamonds, Hearts, Spades }
private final Rank rank;
private final Suit suit;
private Card(Rank r, Suit s){
rank = r; suit = s;
}
public toString();
}
25