Download presentation
Presentation is loading. Please wait.
Published byArnold Crawford Modified over 9 years ago
1
1 Object Oriented Programming Lecture IV Design Patterns, The Observer Observable Pattern, Some notes on Enumeration Types, I/O Streams and Exceptions
2
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
3
3 Today What is a design pattern? A first design pattern –Observer Observable Throwables and Exceptions Type Enumeration
4
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.
5
5 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)
6
6 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
7
7 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); }
8
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
9
9 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
10
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
11
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...
12
12 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!
13
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)
14
14 Exceptions Throwable Error Exception OutOfMemoryError AssertionError Serious Fault! RuntimeException Io-Exception ArithmeticException ClassCastException IndexOutOfBoundsException NullpointerException Thrown By JVM! Any program!
15
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!”); }
16
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.
17
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
18
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
19
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
20
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
21
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
22
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
23
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.
24
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
25
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(); }
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.