1 object oriented programming lecture iv design patterns, the observer observable pattern, some...

25
1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

Upload: arnold-crawford

Post on 27-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

1

Object Oriented ProgrammingLecture IV

Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O

Streams and Exceptions

Page 2: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

2

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

Page 3: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

3

Today

• What is a design pattern?

• A first design pattern– Observer Observable

• Throwables and Exceptions

• Type Enumeration

Page 4: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

4

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.

Page 5: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

5

The Pen Object Example

What functionality do we want when using a pen(interface)?

Constructorpen()

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 penvoid setPaper(Paper p)

Page 6: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

6

Pen is a Mutable ObjectPen 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

Page 7: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

7

Let’s take a look atmove(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);

}

Page 8: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

8

Our first design pattern:Observer-Observable

• Now, let’s examine the properties of a Paper

width

height

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.

Canvas is an AWT component

Page 9: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

9

Observer – ObservableSeparation 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

Page 10: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

10

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

Page 11: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

11

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){ lines.add(new Line(a,b,c,d)); setChanged(); notifyObservers(); } ...

Register the change in Observer!

Notify the Observers!

We have added a line...

Page 12: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

12

The PaperView Classpublic 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!

Page 13: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

13

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)

Page 14: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

14

Exceptions

Throwable

Error

Exception

OutOfMemoryError

AssertionError

Serious Fault!

RuntimeException

Io-Exception

ArithmeticException

ClassCastException

IndexOutOfBoundsException

NullpointerException

Thrown By JVM!

Any program!

Page 15: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

15

Catching Exceptions

Exceptions are caught & handled with a ”try-catch-clause”:

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!”);}

Page 16: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

16

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.

Page 17: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

17

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

• Supports reading/writing sequentially• A stream can only be open for read or write, not both

– Random Access I/O• 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

Page 18: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

18

I/O Byte Streams

• The basic I/O streams are:– Input Stream

• read(); - reads byte• read(byte[] a); - reads byte array• read(byte[] a, int off, int len); - reads part of byte array• skip(long n); - skips over n bytes• close(); - closes the stream

– OutputStream• write(b); - writes byte• write(byte[] a); - writes byte array• write(byte[] a, int off, int len); - writes part of byte array• close(); - closes the stream

Page 19: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

19

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

Page 20: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

20

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

Page 21: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

21

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

Page 22: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

22

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

Page 23: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

23

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.

Page 24: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

24

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

Page 25: 1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions

25

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();}