Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.12.1 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

2 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.22.2 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

3 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.32.3 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; }

4 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.42.4 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);

5 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.52.5 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

6 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.62.6 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

7 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.72.7 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()

8 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.82.8 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

9 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.92.9 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; }

10 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 10 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

11 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 11 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

12 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 12 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; }

13 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 13 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; }

14 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 14 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; }

15 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 15 private DataInputStream makePrimes() {…} private PipeTest(PrintStream out) { DataInputStream fibs = makeFibs(); DataInputStream primes = makePrimes(); try { int x = fibs.readInt(); int y = primes.readInt(); while (x < 100000) { 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); }

16 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 16 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);

17 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 17 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

18 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 18 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: !

19 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 19 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) {}

20 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 20 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

21 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 21 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) {}

22 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 22 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) {}

23 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 23 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

24 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 24 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)

25 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 25 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

26 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 26 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

27 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 27 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

28 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 28 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); }

29 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 29 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

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

31 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 31 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

32 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 32 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

33 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 33 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

34 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 34 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.

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

36 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 36 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.)

37 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 37 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

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

39 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 39 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

40 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 40 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

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

42 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 42 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

43 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 43 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()

44 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 44 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

45 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 45 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

46 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 46 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

47 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 47 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

48 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 48 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();

49 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 49 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);

50 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 50 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); }

51 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 51 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; }

52 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 52 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; }

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

54 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 54 A tree 8 1 23 4567 9 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); }

55 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 55 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

56 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 56 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); }

57 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 57 for(Integer n : tree) System.out.print(n + " "); yields 1 2 4 5 3 6 8 9 7 8 1 23 4567 9 1 2 3 4 5 6 7 8

58 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 58 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(); }

59 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 59 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()); }; }

60 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 60 for(Iterator it = new BfsTreeIterator (tree); it.hasNext(); ) System.out.print(it.next() + " "); yields 1 2 3 4 5 6 7 8 9 8 1 23 4567 9 1 2 3 456 7 8

61 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 61 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

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

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

64 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 64 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) { … }

65 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 65 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); }

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

67 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 67 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); }

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

69 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 69 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)

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

71 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 71 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

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

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

74 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 74 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.

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

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

77 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 77 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

78 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 78 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

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

80 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 80 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

81 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 81 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.

82 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 82 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

83 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 83 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; }

84 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 84 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

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

86 © M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2. 86 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) { }


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

Similar presentations


Ads by Google