COSC 3 P 91 Advanced ObjectOriented Programming IO
COSC 3 P 91 – Advanced Object-Oriented Programming I/O: sequential and random access • streams – sequential – uniform specification for any data transfer • file I/O • network transmission • to/from memory – Input. Stream – Output. Stream © M. Winter 2. 1
COSC 3 P 91 – Advanced Object-Oriented Programming Input streams Input. Stream Byte. Array Input Stream File Input Stream Data Input Stream © M. Winter Filter Input Stream Buffered Input Stream Piped Input Stream Object Input Stream Sequence Input Stream Line. Number Pushback Input Stream 2. 2
COSC 3 P 91 – Advanced Object-Oriented Programming Input streams (cont. ) abstract class Input. Stream { //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 2. 3
COSC 3 P 91 – Advanced Object-Oriented Programming Input streams (cont. ) • Physical input stream – Byte. Array. Input. Stream – File. Input. Stream – Piped. Input. Stream Byte. Array. Input. Stream(byte[] buffer); Byte. Array. Input. Strean(byte[] buffer, int offset, int count); File. Input. Stream(File f); File. Input. Stream(String file. Name); Piped. Input. Stream(Piped. Output. Stream p); © M. Winter 2. 4
COSC 3 P 91 – Advanced Object-Oriented Programming Input streams (cont. ) • Virtual input streams – Sequence. Input. Stream – Object. Input. Stream – Filter. Input. Stream 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 2. 5
COSC 3 P 91 – Advanced Object-Oriented Programming Sequence. Input. Stream - Example Input. Stream f 1 = new File. Input. Stream(“file 1. txt“); Input. Stream f 2 = new File. Input. Stream(“file 2. txt“); Input. Stream f 3 = new Sequence. Input. Stream(f 1, f 2); //f 3 now represents the catenation of file 1 and file 2 Vector fv = new Vector(); fv. add. Element(f 1); fv. add. Element(f 2); Input. Stream f 4 = new Sequence. Input. Stream(fv. elements()); //f 4 also now represents the same catenation © M. Winter 2. 6
COSC 3 P 91 – Advanced Object-Oriented Programming Filter • add behavior to the stream – Data. Input. Stream: read bytes from the source and return them as a primitive type, e. g. , public int read. Int() throws IOException; – Pushback. Input. Stream: allows a single character to be unread. – Buffered. Input. Stream: allows the input operations to backed up over a larger range – mark(), reset() – Line. Number. Input. Stream: deprecated client read() filter read() Input. Stream © M. Winter 2. 7
COSC 3 P 91 – Advanced Object-Oriented Programming Output streams Output. Stream Byte. Array Output Stream File Output Stream Data Output Stream © M. Winter Filter Output Stream Piped Output Stream Object Output Stream Buffered Print Output Stream 2. 8
COSC 3 P 91 – Advanced Object-Oriented Programming Output streams (cont. ) abstract class Output. Stream { //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 2. 9
COSC 3 P 91 – Advanced Object-Oriented Programming Output streams (cont. ) • Physical output stream – Byte. Array. Output. Stream – File. Output. Stream – Piped. Output. Stream • Virtual output streams – Object. Output. Stream – Filter. Output. Stream and its subclasses • Data. Output. Stream: the output equivalent Data. Input. Stream • Buffered. Output. Stream: uses a buffer, values are written to the underlying stream only when the buffer becomes full or when the output is flushed • Print. Stream: similar to Data. Output. Stream but generates a textual representation rather than a binary representation © M. Winter 2. 10
COSC 3 P 91 – 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 Piped. Input. Stream and a Piped. Output. Stream, e. g. , Piped. Input. Stream in = new Piped. Input. Stream(); Piped. Output. Stream out = new Piped. Output. Stream(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, fn+2 = fn + fn+1 © M. Winter 2. 11
COSC 3 P 91 – Advanced Object-Oriented Programming Piped I/O - Example class Fib. Maker extends Thread { private Data. Output. Stream out; public Fib. Maker(Data. Output. Stream o) { out = o; } public void run() { try { out. write. Int(new. Value); out. close(); } catch (IOException e) { return; } } © M. Winter 2. 12
COSC 3 P 91 – Advanced Object-Oriented Programming class Prime. Maker extends Thread { private Data. Output. Stream out; public Prime. Maker(Data. Output. Stream o) { out = o; } public void run() { try { out. write. Int(new. Value); out. close(); } catch (IOException e) { return; } } © M. Winter 2. 13
COSC 3 P 91 – Advanced Object-Oriented Programming class Pipe. Test { public static void main(String[] args) { Pipe. Test world = new Pipe. Test(System. out); } private Data. Input. Stream make. Fibs() { try { Piped. Input. Stream in = new Piped. Input. Stream(); Piped. Output. Stream out = new Piped. Output. Stream(in); Thread fib. Thread = new Fib. Maker( new Data. Output. Stream(out)); fib. Thread. start(); return new Data. Input. Stream(in); } catch (IOException e) { return null; } } © M. Winter 2. 14
COSC 3 P 91 – Advanced Object-Oriented Programming private Data. Input. Stream make. Primes() {…} private Pipe. Test(Print. Stream out) { Data. Input. Stream fibs = make. Fibs(); Data. Input. Stream primes = make. Primes(); try { int x = fibs. read. Int(); int y = primes. read. Int(); while (x < 100000) { if (x == y) { out. println(…); x = fibs. read. Int(); y = primes. read. Int(); } else if (x < y) x = fibs. read. Int(); else y = primes. read. Int(); } } catch (IOException e) { System. exit(0); } } © M. Winter 2. 15
COSC 3 P 91 – Advanced Object-Oriented Programming Character Streams • Reader / Writer mirror the functionality provided by the classes Input. Stream and Output. Stream – 8 -bit bytes versus 16 -bit Unicode character values • Physical Reader / Writer – Char. Array. Reader / Writer – String. Reader / Writer – File. Reader / Writer – Piped. Reader / Writer • Virtual Reader / Writer – Buffered. Reader / Writer – Filter. Reader / Writer – Print. Writer • Input. Stream. Reader / Output. Stream. Writer act as filter for streams, i. e. , they convert streams to character streams, e. g. , File. Input. Stream f = new File. Input. Stream(“file. Name“); Input. Stream. Reader r = new Input. Stream. Reader(f); © M. Winter 2. 16
COSC 3 P 91 – Advanced Object-Oriented Programming Reader Buffered Char. Array Input. Stream Filter Reader Line. Number Reader File Reader Piped Reader String Reader Pushback Reader Writer Buffered Char. Array Output. Stream Filter Writer Piped Print Writer String Writer File Writer © M. Winter 2. 17
COSC 3 P 91 – Advanced Object-Oriented Programming Stream. Tokenizer • Stream. Tokenizer is neither an Input. Stream 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 2. 18
COSC 3 P 91 – Advanced Object-Oriented Programming Reader r = new Input. Stream. Reader(System. in); Stream. Tokenizer tok = new Stream. Tokenizer(r); try { while (tok. next. Token() != 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 2. 19
COSC 3 P 91 – Advanced Object-Oriented Programming Random Access I/O • Random. Access. File – can read & write at same time – implements Data. Input & Data. Output • interfaces which are also implemented by Data. Input. Stream and Data. Output. Stream, 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 • skip. Bytes(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 2. 20
COSC 3 P 91 – Advanced Object-Oriented Programming Examples • copy a file (unfiltered, byte) try { File. Input. Stream in = new File. Input. Stream(“source“); File. Output. Stream out = new File. Output. Stream(“target“); int val = in. read(); while (val != -1) { out. write(val); val = in. read(); }; in. close(); out. close(); } catch (IOException e) {} © M. Winter 2. 21
COSC 3 P 91 – Advanced Object-Oriented Programming Examples • copy a file (buffered Reader / Writer) try { File. Reader fin = new File. Reader(“source“); Buffered. Reader in = new Buffered. Reader(fin); File. Writer fout = new File. Writer(“target“); Buffered. Writer out = new Buffered. Writer(fout); String str = in. read. Line(); while (str != null) { out. write(str); str = in. read. Line(); }; in. close(); out. close(); } catch (IOException e) {} © M. Winter 2. 22
COSC 3 P 91 – 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 2. 23
COSC 3 P 91 – Advanced Object-Oriented Programming Iterator - Model Gamma et al: “Design Patterns: elements of reusable object-oriented software”, p. 259 Aggregate Create. Iterator() Concrete. Aggregate Client Iterator First() Next() Is. Done() Current. Item() Concrete. Iterator Create. Iterator() return new Concrete. Iterator(this) © M. Winter 2. 24
COSC 3 P 91 – 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 • Iterator<E> interface • void for. Each(Consumer<? super T> action) method – who defines traversal algorithm © M. Winter 2. 25
COSC 3 P 91 – Advanced Object-Oriented Programming Iterators • based on Iterator Design Pattern • Iterator public interface Iterator<E> { public boolean has. Next(); public E next(); public void remove(); } – iterator() in Collection – sequential traversal • Enumeration public interface Enumeration<E> { public boolean has. More. Elements(); public E next. Element(); } – functionality of this interface is duplicated by the Iterator interface – new implementations should consider using Iterator in preference to Enumeration © M. Winter 2. 26
COSC 3 P 91 – Advanced Object-Oriented Programming Iterators (cont. ) • List. Iterator public interface List. Iterator<E> extends Iterator<E> { public void add(E o); public boolean has. Previous(); public E previous(); public int next. Index(); public int previous. Index(); public void set(E o); } – list. Iterator() in List – forward and backward sequential traversal © M. Winter 2. 27
COSC 3 P 91 – 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<K, V> { public K get. Key(); public V get. Value(); public V set. Value(V v); } © M. Winter 2. 28
COSC 3 P 91 – 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 – Sort. Display. Factory creates suitable instance depending on the algorithm actually used © M. Winter 2. 29
COSC 3 P 91 – Advanced Object-Oriented Programming Factory - Model Product Factory create. Product() Concrete. Factory create. Product() © M. Winter Creates Concrete. Product 2. 30
COSC 3 P 91 – 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 Widget. Factory that declares interface for each kind of widget • concrete subclasses implement widgets for different look and feel standards • clients call operations in Widget. Factory, remaining independent of actual look and feel © M. Winter 2. 31
COSC 3 P 91 – Advanced Object-Oriented Programming Abstract Factory – Model Gamma et al: “Design Patterns: elements of reusable object-oriented software”, p. 88 Client Abstract. Factory Create. Product. A() Create. Product. B() Abstract. Product. A 2 Concrete. Factory 1 Create. Product. A() Create. Product. B() Concrete. Factory 2 Create. Product. A() Create. Product. B() Abstract. Product. B 2 © M. Winter Product. A 1 Product. B 1 2. 32
COSC 3 P 91 – 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 2. 33
COSC 3 P 91 – 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 2. 34
COSC 3 P 91 – Advanced Object-Oriented Programming Command - Structure Client Invoker Command execute() create Reciever action() receiver Concrete. Command execute() reciever->action() © M. Winter 2. 35
COSC 3 P 91 – Advanced Object-Oriented Programming Command (cont. ) • 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 © M. Winter 2. 36
COSC 3 P 91 – 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 2. 37
COSC 3 P 91 – Advanced Object-Oriented Programming Model-View-Controller Observers a b c x 60 30 10 y 50 30 20 z 80 10 10 b a a b c c a = 50% b = 30% c = 20% change notification requests, modifications Subject © M. Winter 2. 38
COSC 3 P 91 – 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 2. 39
COSC 3 P 91 – Advanced Object-Oriented Programming Observer - Structure Subject observers Attach(Observer) Detach(Observer) Notify() Observer Update() for all o in observers { o->Update() } Concrete. Subject subject Get. State() Set. State() subject. State return subject. State © M. Winter Concrete. Observer Update() observer. State = subject->Get. State() 2. 40
COSC 3 P 91 – Advanced Object-Oriented Programming Observer - Interaction a. Concrete. Subject a. Concrete. Observer another. Concrete. Observer Set. State() Notify() Update() Get. State() © M. Winter 2. 41
COSC 3 P 91 – 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 2. 42
COSC 3 P 91 – Advanced Object-Oriented Programming Strategy - Model Gamma et al: “Design Patterns: elements of reusable object-oriented software”, p. 315 Context. Interface() © M. Winter Strategy Algorithm. Interface() Concrete. Strategy. A Concrete. Strategy. B Concrete. Strategy. C Algorithm. Interface() 2. 43
COSC 3 P 91 – 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 2. 44
COSC 3 P 91 – 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 – compare. To • parameter: a. compare. To(b) • result • total order • consistency with equals © M. Winter 2. 45
COSC 3 P 91 – Advanced Object-Oriented Programming • Comparator public interface Comparator<T> { public int compare(T o 1, T o 2); public boolean equals(Object obj); } – Strategy Design Pattern – compare • parameters c. compare(a, b) • result • total order • consistency with equals © M. Winter 2. 46
COSC 3 P 91 – 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 2. 47
COSC 3 P 91 – Advanced Object-Oriented Programming Composite - Structure Client Component Operation() Add(c : Component) Remove(c : Component) Get. Children() : Collection Leaf Component Operation() forall g in children g. Operation(); children Add(c : Component) Remove(c : Component) Get. Children() : Collection © M. Winter 2. 48
COSC 3 P 91 – Advanced Object-Oriented Programming Example public abstract class Tree<E> implements Iterable<E> { private E element; public Tree(E element) { this. element = element; } public E get. Element() { return element; } public abstract boolean contains(E element); © M. Winter 2. 49
COSC 3 P 91 – Advanced Object-Oriented Programming Example (cont’d) public boolean contains. All(Collection<E> collection) { boolean result = true; for(E element : collection) result &= contains(element); return result; } public abstract int size(); public abstract int depth(); public Iterator<E> iterator() { return new Dfs. Tree. Iterator<E>(this); } } © M. Winter 2. 50
COSC 3 P 91 – Advanced Object-Oriented Programming public class Leaf<E> extends Tree<E> { public Leaf(E element) { super(element); } public boolean contains(E element) { return element. equals(get. Element()); } public int size() { return 1; } public int depth() { return 1; } } © M. Winter 2. 51
COSC 3 P 91 – Advanced Object-Oriented Programming public class Node<E> extends Tree<E> { private Tree<E> left; private Tree<E> right; public Node(E element, Tree<E> left, Tree<E> right) { super(element); this. left = left; this. right = right; } public boolean contains(E element) { return element. equals(get. Element()) || left. contains(element) || right. contains(element); } public int size() { return left. size() + right. size() + 1; } © M. Winter 2. 52
COSC 3 P 91 – Advanced Object-Oriented Programming public int depth() { return Math. max(left. depth(), right. depth()) + 1; } public Tree<E> get. Left. Sub. Tree() { return left; } public Tree<E> get. Right. Sub. Tree() { return right; } } © M. Winter 2. 53
COSC 3 P 91 – Advanced Object-Oriented Programming 1 A tree 2 4 3 5 8 public static Tree<Integer> create. Tree() { Tree<Integer> t 1 = new Leaf<Integer>(8); Tree<Integer> t 2 = new Leaf<Integer>(9); Tree<Integer> t 3 = new Node<Integer>(6, t 1, t 2); Tree<Integer> t 4 = new Leaf<Integer>(7); Tree<Integer> t 5 = new Node<Integer>(3, t 4); Tree<Integer> t 6 = new Leaf<Integer>(4); Tree<Integer> t 7 = new Leaf<Integer>(5); Tree<Integer> t 8 = new Node<Integer>(2, t 6, t 7); return new Node<Integer>(1, t 8, t 5); } © M. Winter 6 7 9 2. 54
COSC 3 P 91 – Advanced Object-Oriented Programming Iterators for Tree public class Dfs. Tree. Iterator<E> implements Iterator<E> { private Iterator<E> iter; public Dfs. Tree. Iterator(Tree<E> tree) { List<E> list = new Array. List<E>(); to. List(tree, list); iter = list. iterator(); } public E next() { return iter. next(); } © M. Winter 2. 55
COSC 3 P 91 – Advanced Object-Oriented Programming public boolean has. Next() { return iter. has. Next(); } public void remove() { throw new Unsupported. Operation. Exception(); } private void to. List(Tree<E> tree, List<E> list) { list. add(tree. get. Element()); if (tree instanceof Node<? >) { to. List(((Node<E>) tree). get. Left. Sub. Tree(), list); to. List(((Node<E>) tree). get. Right. Sub. Tree(), list); } } } © M. Winter 2. 56
COSC 3 P 91 – Advanced Object-Oriented Programming for(Integer n : tree) System. out. print(n + " "); 1 1 2 2 3 4 5 6 7 6 8 8 yields 7 9 1 2 4 5 3 6 8 9 7 © M. Winter 2. 57
COSC 3 P 91 – Advanced Object-Oriented Programming public class Bfs. Tree. Iterator<E> implements Iterator<E> { private Iterator<E> iter; public Bfs. Tree. Iterator(Tree<E> tree) { List<E> list = new Array. List<E>(); Linked. List<Tree<E>> open. List = new Linked. List<Tree<E>>(); open. List. add(tree); to. List(open. List, list); iter = list. iterator(); } public E next() { return iter. next(); } public boolean has. Next() { return iter. has. Next(); } © M. Winter 2. 58
COSC 3 P 91 – Advanced Object-Oriented Programming public void remove() { throw new Unsupported. Operation. Exception(); } private void to. List(Linked. List<Tree<E>> open. List, List<E> list) { while (!open. List. is. Empty()) { Tree<E> tree = open. List. remove. First(); list. add(tree. get. Element()); if (tree instanceof Node<? >) { open. List. add. Last( ((Node<E>) tree). get. Left. Sub. Tree()); open. List. add. Last( ((Node<E>) tree). get. Right. Sub. Tree()); }; } } } © M. Winter 2. 59
COSC 3 P 91 – Advanced Object-Oriented Programming for(Iterator<Integer> it = new Bfs. Tree. Iterator<Integer>(tree); it. has. Next(); ) System. out. print(it. next() + " "); 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 yields 8 9 1 2 3 4 5 6 7 8 9 © M. Winter 2. 60
COSC 3 P 91 – 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 2. 61
COSC 3 P 91 – Advanced Object-Oriented Programming Decorator - Structure Component Operation() Concrete. Component Decorator Operation() component. Operation(); Concrete. Decorator. A Concrete. Decorator. B added. State Operation() Added. Behavior(); Operation() super. Operation(); Added. Behavior(); © M. Winter 2. 62
COSC 3 P 91 – Advanced Object-Oriented Programming Example public interface Shape { public Rectangle bounding. Box(); public double area(); public void draw(Graphics 2 D g); } © M. Winter 2. 63
COSC 3 P 91 – 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; } public Rectangle bounding. Box() { int x = (int) location. x – radius; int y = (int) location. y – radius; int width = (int) 2*radius; return new Rectangle(x, y, width); } public void draw(Graphics 2 D g) { … } } © M. Winter 2. 64
COSC 3 P 91 – Advanced Object-Oriented Programming public class Decorated. Shape implements Shape { private Shape shape; public Decorated. Shape(Shape s) { shape = s; } public double area() { return shape. area(); } public Rectangle bounding. Box() { return shape. bounding. Box(); } public void draw(Graphics 2 D g) { shape. draw(g); } } © M. Winter 2. 65
COSC 3 P 91 – Advanced Object-Oriented Programming public class Framed. Shape extends Decorated. Shape { public Framed. Shape(Shape s) { super(s); } public void draw(Graphics 2 D g) { super. draw(g); g. draw(bounding. Box()); } } © M. Winter 2. 66
COSC 3 P 91 – Advanced Object-Oriented Programming public class Area. Shape extends Decorated. Shape { public Area. Shape(Shape s) { super(s); } public void draw(Graphics 2 D g) { super. draw(g); int x = …; int y = …; g. draw. String(”Area: ”+area(). to. String(), x, y); } } © M. Winter 2. 67
COSC 3 P 91 – Advanced Object-Oriented Programming Shape s = new Area. Shape( new Framed. Shape (new Circle(10, 1. 0))); s. draw(g); Area: 3. 1415926 © M. Winter 2. 68
COSC 3 P 91 – 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. – Text. Shape as adapted Text. View in a drawing editor – Shape hierarchy – existing Text. View class • modify Text. View class? – Text. Shape as adapter • via inheritance (class adapter) • via composition (object adapter) © M. Winter 2. 69
COSC 3 P 91 – Advanced Object-Oriented Programming Text. Shape as Adapter Drawing. Editor Shape Text. View bounding. Box() create. Manipulator() get. Extent() Line Text. Shape bounding. Box() create. Manipulator() text return text. get. Extent() return new Text. Manipulator © M. Winter 2. 70
COSC 3 P 91 – 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 Adaptees (Adaptee class and any subclass), adding functionality to all Adaptees at once • harder to override Adaptee behavior, i. e. the subclasses may also override so must adapt each subclass as well © M. Winter 2. 71
COSC 3 P 91 – Advanced Object-Oriented Programming Class Adapter Client Target Adaptee request() specific. Request() (implementation) Adapter request() © M. Winter specific. Request() 2. 72
COSC 3 P 91 – Advanced Object-Oriented Programming Object Adapter Client Target Adaptee request() specific. Request() adaptee Adapter request() © M. Winter adaptee. specific. Request() 2. 73
COSC 3 P 91 – 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 2. 74
COSC 3 P 91 – Advanced Object-Oriented Programming Façade Motivation client classes Façade subsystem classes © M. Winter 2. 75
COSC 3 P 91 – Advanced Object-Oriented Programming Compiler as Façade Compiler Compile() compiler subsystem classes Stream Scanner Token Parser Symbol Program. Node. Builder Program. Node Byte. Code. Stream Code. Generator Statement. Node Expression. Node Variable. Node Stack. Machine. Code. Generator © M. Winter RISCCode. Generator 2. 76
COSC 3 P 91 – 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 2. 77
COSC 3 P 91 – 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 Audio. Clip. Manager is responsible for playing audio clips – a previous clip is stopped before a new one is started – ensure that there is just one Audio. Clip. Manager © M. Winter 2. 78
COSC 3 P 91 – Advanced Object-Oriented Programming Example (Audio. Clip. Manager) Audio. Clip. Manager -instance : Audio. Clip. Manager -clip : Audio. Clip -Audio. Clip. Manager() +get. Instance() : Audio. Clip. Manager +play(: Audio. Clip) +stop() return instance . . . © M. Winter 2. 79
COSC 3 P 91 – Advanced Object-Oriented Programming Singleton – Structure & Considerations Singleton -instance : Singleton -Singleton() +get. Instance() : Singleton. . . • • • return instance lazy instantiation – create instance at load-time vs postpone creation until the first call of get. Instance() 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 © M. Winter 2. 80
COSC 3 P 91 – 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 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 2. 81
COSC 3 P 91 – Advanced Object-Oriented Programming Singleton - Example The class Universal. Counter should provide a sole instance which • is capable of counting globally calls of the inc. Count() method • • works in a multi-thread environment uses lazy instantiation Additional considerations: • lazy instantiation and counting in a concurrent environment © M. Winter 2. 82
COSC 3 P 91 – Advanced Object-Oriented Programming public class Universal. Counter { private static Universal. Counter my. Instance = null; private int count ; private Universal. Counter() { count = 0; } public static synchronized Universal. Counter get. Instance() { if (my. Instance == null) my. Instance = new Universal. Counter(); return my. Instance; } public synchronized void inc. Count() { count++; } public int get. Count() { return count; } } © M. Winter 2. 83
COSC 3 P 91 – 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 2. 84
COSC 3 P 91 – Advanced Object-Oriented Programming Null object - Structure Delegator Example uses 1 1 Operation. IF Application uses 1 1 Warning. Router route. Warning(: String) Null. Operation Real. Operation Warning. Dialog Ignore. Warning © M. Winter Warning. Logger 2. 85
COSC 3 P 91 – Advanced Object-Oriented Programming Null object - Example public interface Warning. Router { public void route. Warning(String msg); } public class Warning. Dialog implements Warning. Router { public void route. Warning(String msg) { JOption. Pane. show. Message. Dialog(null, msg, ”Warning”, JOption. Pane. OK_OPTION, JOption. Pane. WARNING_MESSAGE); } } public class Warning. Logger implements Warning. Router {. . . } public class Ignore. Warning implements Warning. Router { public void route. Warning(String msg) { } } © M. Winter 2. 86
- Slides: 86