© M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.12.1 I/O I/O: sequential and random access streams –sequential –uniform specification for.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
1 Structural Design Patterns - Neeraj Ray. 2 Structural Patterns - Overview n Adapter n Bridge n Composite n Decorator.
02 - Structural Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Plab – Tirgul 12 Design Patterns
1 CS 501 Spring 2005 CS 501: Software Engineering Lecture 17 Object Oriented Design 3.
. Plab – Tirgul 12 Design Patterns. Design Patterns u The De-Facto Book on Design Patterns:
CS CS 5150 Software Engineering Lecture 17 Object Oriented Design 3.
1 CS 501 Spring 2008 CS 501: Software Engineering Lectures 17 & 18 Object Oriented Design 3 & 4.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
Design Patterns. CS351 - Software Engineering (AY2007)Slide 2 Behavioral patterns Suppose we have an aggregate data structure and we wish to access the.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
1 CS 501 Spring 2007 CS 501: Software Engineering Lectures 17 & 18 Object Oriented Design 3 & 4.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
More OOP Design Patterns
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
© SERG Software Design (OOD Patterns) Object-Oriented Design Patterns Topics in Object-Oriented Design Patterns Compliments of Spiros Mancoridis Material.
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
Design Patterns.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Structural Design Patterns
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IV Structural Patterns.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
Design Pattern. Definition: A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
Lecture 14 Inheritance vs Composition. Inheritance vs Interface Use inheritance when two objects share a structure or code relation Use inheritance when.
© SERG Software Design (OOD Patterns) Pg 1 Object-Oriented Design Patterns Topics in Object-Oriented Design Patterns Material drawn from [Gamma95,Coplien95]
Advanced Object-oriented Design Patterns Creational Design Patterns.
The Facade Pattern (Structural) ©SoftMoore ConsultingSlide 1.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
CS 5150 Software Engineering Lecture 16 Program Design 3.
Reference – Object Oriented Software Development Using Java - Jia COP 3331 Object Oriented Analysis and Design Chapter 10 – Patterns Jean Muhammad.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
Abstract Factory pattern Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
The Java IO System Different kinds of IO Different kinds of operations
Examples (D. Schmidt et al)
Design Patterns: Brief Examples
Factory Patterns 1.
I/O Basics.
Object-Oriented Design Patterns
More Design Patterns 1.
Design Patterns - A few examples
More Design Patterns 1.
I/O I/O: sequential and random access streams sequential
Files and Streams in Java
Presentation transcript:

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming I/O I/O: sequential and random access streams –sequential –uniform specification for any data transfer file I/O network transmission to/from memory –InputStream –OutputStream

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Input streams InputStream ByteArray Input Stream File Input Stream Filter Input Stream Piped Input Stream Object Input Stream Sequence Input Stream Data Input Stream Buffered Input Stream LineNumber Input Stream Pushback Input Stream

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Input streams (cont.) abstract class InputStream { //read a singe byte from the input int read() throws IOException; //read an array of values from the input int read(byte[] buffer) throws IOException; //skip the indicated number of values from input long skip(long n) throws IOException; //determine number of bytes readable without blocking int available() throws IOException; //close this input stream void close() throws IOException; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Input streams (cont.) Physical input stream –ByteArrayInputStream –FileInputStream –PipedInputStream ByteArrayInputStream(byte[] buffer); ByteArrayInputStrean(byte[] buffer, int offset, int count); FileInputStream(File f); FileInputStream(String fileName); PipedInputStream(PipedOutputStream p);

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Input streams (cont.) Virtual input streams –SequenceInputStream –ObjectInputStream –FilterInputStream and its subclasses do not read values from any input area rely on one or more underlying input streams are implementations of the design patter decorator

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming SequenceInputStream - Example InputStream f1 = new FileInputStream(“file1.txt“); InputStream f2 = new FileInputStream(“file2.txt“); InputStream f3 = new SequenceInputStream(f1,f2); //f3 now represents the catenation of file1 and file2 Vector fv = new Vector(); fv.addElement(f1); fv.addElement(f2); InputStream f4 = new SequenceInputStream(fv.elements()); //f4 also now represents the same catenation

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Filter add behavior to the stream –DataInputStream : read bytes from the source and return them as a primitive type, e.g., public int readInt() throws IOException; –PushbackInputStream : allows a single character to be unread. –BufferedInputStream : allows the input operations to backed up over a larger range – mark(), reset() –LineNumberInputStream : deprecated InputStream filter client read()

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Output streams OutputStream ByteArray Output Stream File Output Stream Filter Output Stream Piped Output Stream Object Output Stream Data Output Stream Buffered Output Stream Print Stream

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Output streams (cont.) abstract class OutputStream { //write a singe byte value void write(int b) throws IOException; //write an array of byte values void write(byte[] buffer) throws IOException; //flush all output from buffers void flush() throws IOException; //close this output stream void close() throws IOException; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Output streams (cont.) Physical output stream –ByteArrayOutputStream –FileOutputStream –PipedOutputStream Virtual output streams –ObjectOutputStream –FilterOutputStream and its subclasses DataOutputStream : the output equivalent DataInputStream BufferedOutputStream : uses a buffer, values are written to the underlying stream only when the buffer becomes full or when the output is flushed PrintStream : similar to DataOutputStream but generates a textual representation rather than a binary representation

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Piped input and output used for producer/consumer relationships –communication between producer and consumer (different threads) through a pipe each pipe is manifested by a matched pair of stream pointers, a PipedInputStream and a PipedOutputStream, e.g., PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); Example: finding all numbers that are both prime numbers and Fibonacci numbers, i.e., a number defined by the recursive relation f 0 = 0, f 1 = 1, f n+2 = f n + f n+1

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Piped I/O - Example class FibMaker extends Thread { private DataOutputStream out; public FibMaker(DataOutputStream o) { out = o; } public void run() { try { out.writeInt(newValue); out.close(); } catch (IOException e) { return; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming class PrimeMaker extends Thread { private DataOutputStream out; public PrimeMaker(DataOutputStream o) { out = o; } public void run() { try { out.writeInt(newValue); out.close(); } catch (IOException e) { return; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming class PipeTest { public static void main(String[] args) { PipeTest world = new PipeTest(System.out); } private DataInputStream makeFibs() { try { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); Thread fibThread = new FibMaker( new DataOutputStream(out)); fibThread.start(); return new DataInputStream(in); } catch (IOException e) { return null; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming private DataInputStream makePrimes() {…} private PipeTest(PrintStream out) { DataInputStream fibs = makeFibs(); DataInputStream primes = makePrimes(); try { int x = fibs.readInt(); int y = primes.readInt(); while (x < ) { if (x == y) { out.println(…); x = fibs.readInt(); y = primes.readInt(); } else if (x < y) x = fibs.readInt(); else y = primes.readInt(); } } catch (IOException e) { System.exit(0); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Character Streams Reader / Writer mirror the functionality provided by the classes InputStream and OutputStream –8-bit bytes versus 16-bit Unicode character values Physical Reader / Writer –CharArrayReader / Writer –StringReader / Writer –FileReader / Writer –PipedReader / Writer Virtual Reader / Writer –BufferedReader / Writer –FilterReader / Writer –PrintWriter InputStreamReader / OutputStreamWriter act as filter for streams, i.e., they convert streams to character streams, e.g., FileInputStream f = new FileInputStream(“fileName“); InputStreamReader r = new InputStreamReader(f);

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Writer Buffered Writer CharArray Writer OutputStream Writer Filter Writer Print Writer File Writer Reader Buffered Reader CharArray Reader InputStream Reader Filter Reader Piped Reader String Reader File Reader LineNumber Reader Pushback Reader String Writer Piped Writer

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming StreamTokenizer StreamTokenizer is neither an InputStream nor a Reader provides a useful mechanism for breaking a textual file into a sequence of tokens. Example: “23-skidoo, kid!” yields the output: number: 23.0 token: - word: skidoo token:, word: kid token: !

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Reader r = new InputStreamReader(System.in); StreamTokenizer tok = new StreamTokenizer(r); try { while (tok.nextToken() != tok.TT_EOF) { switch (tok.ttype) { case tok.TT_NUMBER: System.out.println(“number: “ + tok.nval); break; case tok.TT_EOL: System.out.println(“end of line.“); break; case tok.TT_WORD: System.out.println(“word: “ + tok.sval); break; default: System.out.println(“token: “ + (char) tok.ttype); break; } } catch (IOException e) {}

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Random Access I/O RandomAccessFile –can read & write at same time –implements DataInput & DataOutput interfaces which are also implemented by DataInputStream and DataOutputStream, respectively –changing current I/O position seek(l) moves the read/write position to the l -th byte counting from the beginning of the file skipBytes(i) moves the read/write position i bytes relative to the current position storing serialized objects in random access files –Idea: write object as size followed by serialized version –Implementation: X. Jia, Object-Oriented Software Development using Java, 8.4.4

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Examples copy a file (unfiltered, byte) try { FileInputStream in = new FileInputStream(“source“); FileOutputStream out = new FileOutputStream(“target“); int val = in.read(); while (val != -1) { out.write(val); val = in.read(); }; in.close(); out.close(); } catch (IOException e) {}

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Examples copy a file (buffered Reader / Writer ) try { FileReader fin = new FileReader(“source“); BufferedReader in = new BufferedReader(fin); FileWriter fout = new FileWriter(“target“); BufferedWriter out = new BufferedWriter(fout); String str = in.readLine(); while (str != null) { out.write(str); str = in.readLine(); }; in.close(); out.close(); } catch (IOException e) {}

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design Pattern – Iterator aka Cursor a behavioral pattern intent: –allow sequential access to elements of an aggregate without exposing underlying representation motivation: –want to be able to access elements of an aggregate object without exposing internal structure –want to use several different traversals –want different traversals pending on same list

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Iterator - Model Gamma et al: “Design Patterns: elements of reusable object-oriented software”, p.259 Aggregate CreateIterator() Iterator First() Next() IsDone() CurrentItem() Client ConcreteIterator ConcreteAggregate CreateIterator() return new ConcreteIterator(this)

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming use: –access aggregate object’s contents without exposing internal representation –support multiple traversals of aggregate objects –provide uniform interface for traversing different structures model consequences: –supports variations in traversal of aggregate –simplified aggregate interface –more than one traversal can be pending on an aggregate considerations: –internal versus external iterators –who defines traversal algorithm

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Iterators based on Iterator Design Pattern Iterator public interface Iterator { public boolean hasNext(); public E next(); public void remove(); } –iterator() in Collection –sequential traversal Enumeration public interface Enumeration { public boolean hasMoreElements(); public E nextElement(); } –functionality of this interface is duplicated by the Iterator interface –new implementations should consider using Iterator in preference to Enumeration

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Iterators (cont.) ListIterator public interface ListIterator extends Iterator { public void add(E o); public boolean hasPrevious(); public E previous(); public int nextIndex(); public int previousIndex(); public void set(E o); } –listIterator() in List –forward and backward sequential traversal

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Iterators (cont.) iterating through Map views –views key set value collection entry set (nested interface Map.Entry ) public static interface Map.Entry { public K getKey(); public V getValue(); public V setValue(V v); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design Pattern - Factory a creational pattern intent: –To define an interface for creating objects but let subclasses decide which class to instantiate and how motivation: –Display classes for different sorting algorithms –SortDisplayFactory creates suitable instance depending on the algorithm actually used

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Factory - Model Factory createProduct() ConcreteFactory createProduct() Product ConcreteProduct Creates

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design pattern - Abstract Factory aka Kit a creational pattern intent: –provide interface for creating families of related objects without specifying concrete representation motivation: –toolkit that supports multiple standards –e.g. look and feel of widgets define WidgetFactory that declares interface for each kind of widget concrete subclasses implement widgets for different look and feel standards clients call operations in WidgetFactory, remaining independent of actual look and feel

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Abstract Factory – Model Gamma et al: “Design Patterns: elements of reusable object-oriented software”, p.88 AbstractFactory CreateProductA() CreateProductB() ProductB1 ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() ProductB2 AbstractProductB ProductA1 ProductA2 AbstractProductA Client

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming use: –system should be independent of how products are created, composed and represented –family of products designed to be used together –want to provide library of products and reveal only interfaces not implementation model consequences –isolates concrete classes –easy to exchange product “families” –promotes consistency among products –difficult to support new kinds of products

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design pattern - Command aka Action a behavioral pattern intent: –To encapsulate an action as an object, so that actions can be passed as parameters, queued, and possible undone Use the Command design pattern –when actions need to be passed as parameters. –when actions need to be queued and then executed later. –when actions can be undone.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Command - Structure Command execute() ConcreteCommand execute() reciever->action() Invoker Reciever action() Client receiver create

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming use: –parameterize objects by actions to perform –specify, queue, and execute requests at different times –support undo consequences –command are first-class objects –you can assemble commands into a composite command (design pattern – composite) –easy to add new commands Command (cont.)

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design pattern - Observer aka Dependents, Publish-and-Subscribe a behavioral pattern intent: –define dependencies between objects –when an object changes state, ensure all dependents are notified and updated motivation: –need to maintain consistency among cooperating classes –e.g. MVC GUI model multiple views of same data –multiple windows on same text file subject observers

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Model-View-Controller Observers Subject a = 50% b = 30% c = 20% a b c x y z a b c a c b change notification requests, modifications

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming use: –abstraction has two aspects, one dependent on the other –change to an object requires changing an unknown number of others –object needs to notify other objects without knowing details about them consequences –abstract coupling between Subject and Observer –broadcast communication –unexpected updates considerations –mapping subjects to observers –observing more than one subject –triggering the update –deleted subjects –self-consistent state in subject –how much information to send on update

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Observer - Structure Subject Attach(Observer) Detach(Observer) Notify() Observer Update() ConcreteSubject GetState() SetState() subjectState return subjectStatefor all o in observers { o->Update() } ConcreteObserver Update() observerState observerState = subject->GetState() observers subject

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Observer - Interaction aConcreteSubject aConcreteObserver anotherConcreteObserver SetState() Update() Notify() GetState()

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design Pattern – Strategy aka Policy a behavioral pattern intent: –allow different variants of an algorithm motivation: –different traversals for sorted aggregates based on different orderings –it is difficult to add new orderings or vary existing once when they are an integral part of the traversal

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Strategy - Model Gamma et al: “Design Patterns: elements of reusable object-oriented software”, p.315 Context ContextInterface() Strategy AlgorithmInterface() ConcreteStrategyB AlgorithmInterface() ConcreteStrategyC AlgorithmInterface() ConcreteStrategyA AlgorithmInterface()

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming use: –many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors. –you need different variants of an algorithm. –an algorithm uses data that clients shouldn’t know about. –a class defines many behaviors, and these appear as multiple conditional statements in its operations. model consequences: –hierarchies of strategies classes define a family of algorithms or behaviors for contexts to reuse. –an alternative to subclassing –eliminates conditional statements –choice of implementations considerations: –clients must be aware of different strategies –communication overhead between Strategy and Context –increased number of objects

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Ordering and Sorting order (partial order) –total order versus strictly partial order natural order –by implementing Comparable interface imposed order –by use of Comparator Comparable –compareTo parameter: a.compareTo(b) result total order consistency with equals

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Comparator public interface Comparator { public int compare(T o1, T o2); public boolean equals(Object obj); } –Strategy Design Pattern –compare parameters c.compare(a,b) result total order consistency with equals

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design pattern - composite Intent: –compose objects into tree structures to represent part-whole hierarchies. use the composite pattern when –you want to represent part-whole hierarchies of objects –you want clients to be able to ignore the difference between compositions of objects and individual objects

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Composite - Structure Client Operation() Add(c : Component) Remove(c : Component) GetChildren() : Collection Component Operation() Add(c : Component) Remove(c : Component) GetChildren() : Collection Component Operation() Leaf children forall g in children g.Operation();

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example public abstract class Tree implements Iterable { private E element; public Tree(E element) { this.element = element; } public E getElement() { return element; } public abstract boolean contains(E element);

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example (cont’d) public boolean containsAll(Collection collection) { boolean result = true; for(E element : collection) result &= contains(element); return result; } public abstract int size(); public abstract int depth(); public Iterator iterator() { return new DfsTreeIterator (this); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class Leaf extends Tree { public Leaf(E element) { super(element); } public boolean contains(E element) { return element.equals(getElement()); } public int size() { return 1; } public int depth() { return 1; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class Node extends Tree { private Tree left; private Tree right; public Node(E element, Tree left, Tree right) { super(element); this.left = left; this.right = right; } public boolean contains(E element) { return element.equals(getElement()) || left.contains(element) || right.contains(element); } public int size() { return left.size() + right.size() + 1; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public int depth() { return Math.max(left.depth(),right.depth()) + 1; } public Tree getLeftSubTree() { return left; } public Tree getRightSubTree() { return right; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming A tree public static Tree createTree() { Tree t1 = new Leaf (8); Tree t2 = new Leaf (9); Tree t3 = new Node (6,t1,t2); Tree t4 = new Leaf (7); Tree t5 = new Node (3,t3,t4); Tree t6 = new Leaf (4); Tree t7 = new Leaf (5); Tree t8 = new Node (2,t6,t7); return new Node (1,t8,t5); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class DfsTreeIterator implements Iterator { private Iterator iter; public DfsTreeIterator(Tree tree) { List list = new ArrayList (); toList(tree,list); iter = list.iterator(); } public E next() { return iter.next(); } Iterators for Tree

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public boolean hasNext() { return iter.hasNext(); } public void remove() { throw new UnsupportedOperationException(); } private void toList(Tree tree, List list) { list.add(tree.getElement()); if (tree instanceof Node ) { toList(((Node ) tree).getLeftSubTree(),list); toList(((Node ) tree).getRightSubTree(),list); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming for(Integer n : tree) System.out.print(n + " "); yields

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class BfsTreeIterator implements Iterator { private Iterator iter; public BfsTreeIterator(Tree tree) { List list = new ArrayList (); LinkedList > openList = new LinkedList >(); openList.add(tree); toList(openList,list); iter = list.iterator(); } public E next() { return iter.next(); } public boolean hasNext() { return iter.hasNext(); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public void remove() { throw new UnsupportedOperationException(); } private void toList(LinkedList > openList, List list) { while (!openList.isEmpty()) { Tree tree = openList.removeFirst(); list.add(tree.getElement()); if (tree instanceof Node ) { openList.addLast( ((Node ) tree).getLeftSubTree()); openList.addLast( ((Node ) tree).getRightSubTree()); }; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming for(Iterator it = new BfsTreeIterator (tree); it.hasNext(); ) System.out.print(it.next() + " "); yields

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design pattern – Decorator aka filter, wrapper Intent: –attach additional responsibilities to an object dynamically. use Decorator –to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects –for responsibilities that can be withdrawn –when extension by subclassing is impractical

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Decorator - Structure Operation() Component Operation() ConcreteComponent component Operation() Decorator Operation() AddedBehavior(); ConcreteDecoratorB addedState ConcreteDecoratorA Operation() component.Operation(); super.Operation(); AddedBehavior();

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example public interface Shape { public Rectangle boundingBox(); public double area(); public void draw(Graphics2D g); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class Circle implements Shape { private Point location; private double radius; public Circle(int x; int y; double rad) { location = new Point(x,y); radius = rad; } public double area() { return Math.pi * radius * radius; } public Rectangle boundingBox() { int x = (int) location.x – radius; int y = (int) location.y – radius; int width = (int) 2*radius; return new Rectangle(x,y,width,width); } public void draw(Graphics2D g) { … }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class DecoratedShape implements Shape { private Shape shape; public DecoratedShape(Shape s) { shape = s; } public double area() { return shape.area(); } public Rectangle boundingBox() { return shape.boundingBox(); } public void draw(Graphics2D g) { shape.draw(g); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class FramedShape extends DecoratedShape { public FramedShape(Shape s) { super(s); } public void draw(Graphics2D g) { super.draw(g); g.draw(boundingBox()); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class AreaShape extends DecoratedShape { public AreaShape(Shape s) { super(s); } public void draw(Graphics2D g) { super.draw(g); int x = …; int y = …; g.drawString(”Area: ”+area().toString(),x,y); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Shape s = new AreaShape( new FramedShape (new Circle(10,10,1.0))); s.draw(g); Area:

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Adapter aka Wrapper a structural pattern intent: convert interface of a class into another interface clients expect motivation: –sometimes object provides appropriate behavior but uses a different interface than is required e.g. – TextShape as adapted TextView in a drawing editor –Shape hierarchy –existing TextView class modify TextView class? –TextShape as adapter via inheritance (class adapter) via composition (object adapter)

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming TextShape as Adapter DrawingEditor TextShape boundingBox() createManipulator() TextView getExtent() Line boundingBox() createManipulator() Shape boundingBox() createManipulator() return new TextManipulatorreturn text.getExtent() text

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming use: –want to use existing class without proper interface –want to create reusable class that cooperates with unrelated or unforeseen classes –want to use several existing subclasses but impractical to adapt interface by subclassing every one model consequences: –class adapter (inheritance) commits to a concrete Adaptee class, can’t adapt class and all subclasses Adapter can override behavior (inheritance) only one object created –object adapter (composition) Adapter can work with multiple Adaptee s ( Adaptee class and any subclass), adding functionality to all Adaptee s at once harder to override Adaptee behavior, i.e. the subclasses may also override so must adapt each subclass as well

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Class Adapter Target request() Client Adapter request() Adaptee specificRequest() (implementation)

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Object Adapter Target request() Client Adapter request() Adaptee specificRequest() adaptee.specificRequest() adaptee

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Façade a structural pattern intent: –provide a unified interface to a set of interfaces in a subsystem motivation: –most clients don’t care about details –powerful, low-level interfaces complicate task –e.g. Compiler is façade for Scanner, Parser, etc.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Façade Motivation Façade subsystem classes client classes

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Compiler as Façade compiler subsystem classes Compiler Compile() Stream CodeGenerator ByteCodeStream RISCCodeGeneratorStackMachineCodeGenerator VariableNode ExpressionNode StatementNode ProgramNodeProgramNodeBuilder SymbolParser ScannerToken

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming use: –want to provide a simple interface to a complex subsystem –there are many dependencies between clients and implementation classes model –Façade common interface to all subsystem functions delegates to appropriate subsystem object –subsystem classes implement subsystem functionality have no knowledge of Façade consequences: –shields clients from subsystem components, making subsystem easier to use –promotes weak coupling between subsystem and clients –eliminate complex dependencies Java API –java.net URL class allows access to URLs without knowing the classes which support URLs

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Singleton a creational pattern intent: Ensure a class only has one instance, and provide a global point of access to it. motivation: –Some classes should have exactly one instance. These classes usually involve the central management of a resource. e.g. –just one audio clip should be played at a time –an object of the class AudioClipManager is responsible for playing audio clips – a previous clip is stopped before a new one is started –ensure that there is just one AudioClipManager

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example ( AudioClipManager ) AudioClipManager -instance : AudioClipManager -clip : AudioClip -AudioClipManager() +getInstance() : AudioClipManager +play(: AudioClip) +stop()... return instance

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Singleton – Structure & Considerations lazy instantiation –create instance at load-time vs postpone creation until the first call of getInstance() interface Clonable –a singleton object should not implement this interface Object serialization –serialization can be used to copy objects –a singleton object should not implement the interface Serializable Singleton -instance : Singleton -Singleton() +getInstance() : Singleton... return instance

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Singleton - Consequences Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it. Reduced name space. The singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances. Permits refinement of operations and representation. The Singleton class may be subclassed, and it is easy to configure an application with instances of this extended class. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class (variation: up to a fixed number n of instances). Only the operation that grants access to the Singleton instance needs to change. More flexible than class operations. Another way to package a singleton’s functionality is to use class operations. This approach makes it hard to change a design to allow more than one instance.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Singleton - Example The class UniversalCounter should provide a sole instance which is capable of counting globally calls of the incCount() method works in a multi-thread environment uses lazy instantiation Additional considerations: lazy instantiation and counting in a concurrent environment

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class UniversalCounter { private static UniversalCounter myInstance = null; private int count ; private UniversalCounter() { count = 0; } public static synchronized UniversalCounter getInstance() { if (myInstance == null) myInstance = new UniversalCounter(); return myInstance; } public synchronized void incCount() { count++; } public int getCount() { return count; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Null object a behavioral pattern intent: The null object pattern provides an alternative to using null to indicate the absence of an object. motivation: –using null to indicate the absence of an object requires a test for null before calling a method. e.g. –we want to provide a facility which is able to route warnings/error messages to different locations dialog box a log file nowhere at all … –the user of this class/package should not forced to test for null before using it

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Null object - Structure Delegator OperationIF NullOperationRealOperation 1 1 uses  Application WarningRouter routeWarning(:String) IgnoreWarning WarningDialog 1 1 uses  WarningLogger Example

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Null object - Example public interface WarningRouter { public void routeWarning(String msg); } public class WarningDialog implements WarningRouter { public void routeWarning(String msg) { JOptionPane.showMessageDialog(null, msg, ”Warning”, JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE); } public class WarningLogger implements WarningRouter {...} public class IgnoreWarning implements WarningRouter { public void routeWarning(String msg) { }