© M. Winter COSC 3P91 – Advanced Object-Oriented Programming 2.12.1 I/O I/O: sequential and...

Preview:

Citation preview

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.3

Input streams (cont.)abstract class InputStream {

//read a singe byte from the inputint read() throws IOException;

//read an array of values from the inputint read(byte[] buffer) throws IOException;

//skip the indicated number of values from inputlong skip(long n) throws IOException;

//determine number of bytes readable without blockingint available() throws IOException;

//close this input streamvoid close() throws IOException;

}

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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);

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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()

read()

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.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;

}

© 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

© 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

f0 = 0, f1 = 1,

fn+2 = fn + fn+1

© 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;

}

}

© 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;

}}

© 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;

}

}

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

elsey = primes.readInt();

}} catch (IOException e) {

System.exit(0);}

}

© 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);

© 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

© 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.0token: -word: skidootoken: ,word: kidtoken: !

© 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) {}

© 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

© 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) {}

© 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) {}

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.24

Iterator - ModelGamma et al: “Design Patterns: elements of reusable object-oriented software”, p.259

Aggregate

CreateIterator()

Iterator

First()Next()IsDone()CurrentItem()

Client

ConcreteIteratorConcreteAggregate

CreateIterator()

return new ConcreteIterator(this)

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.26

Iterators• based on Iterator Design Pattern• Iterator

public interface Iterator<E> {public boolean hasNext();public E next();public void remove();

}– iterator() in Collection– sequential traversal

• Enumerationpublic interface Enumeration<E> {

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

2.27

Iterators (cont.)

• ListIterator

public interface ListIterator<E> extends Iterator<E> {

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

2.28

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

public V getValue();

public V setValue(V v);

}

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.30

Factory - Model

Factory

createProduct()

ConcreteFactory

createProduct()

Product

ConcreteProductCreates

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.32

Abstract Factory – ModelGamma et al: “Design Patterns: elements of reusable object-oriented software”, p.88

AbstractFactory

CreateProductA()CreateProductB()

ProductB1

ConcreteFactory1

CreateProductA()CreateProductB()

ConcreteFactory2

CreateProductA()CreateProductB()

ProductB2

AbstractProductB

ProductA1ProductA2

AbstractProductA

Client

© 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

© 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.

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.35

Command - Structure

Command

execute()

ConcreteCommand

execute()

reciever->action()

Invoker

Reciever

action()

Client

receiver

create

© 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.)

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.38

Model-View-Controller

Observers

Subject

a = 50%b = 30%c = 20%

a b cx 60 30 10y 50 30 20z 80 10 10

a b ca c

b

change notification

requests, modifications

© 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

© 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 subjectState

for all o in observers { o->Update()}

ConcreteObserver

Update()

observerState

observerState = subject->GetState()

observers

subject

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.41

Observer - Interaction aConcreteSubject aConcreteObserver anotherConcreteObserver

SetState()

Update()

Update()

Notify()

GetState()

GetState()

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.43

Strategy - ModelGamma 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

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

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.46

• Comparator

public interface Comparator<T> {

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

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

© 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()

Leafchildren

forall g in children

g.Operation();

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.49

Example

public abstract class Tree<E> implements Iterable<E> {

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

2.50

Example (cont’d)

public boolean containsAll(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 DfsTreeIterator<E>(this);

}

}

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.51

public class Leaf<E> extends Tree<E> {

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

2.52

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(getElement()) || left.contains(element) || right.contains(element);

}

public int size() {

return left.size() + right.size() + 1;

}

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.53

public int depth() {

return Math.max(left.depth(),right.depth()) + 1;

}

public Tree<E> getLeftSubTree() {

return left;

}

public Tree<E> getRightSubTree() {

return right;

}

}

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.54

A tree

8

1

2 3

4 5 6 7

9public static Tree<Integer> createTree() {

Tree<Integer> t1 = new Leaf<Integer>(8);Tree<Integer> t2 = new Leaf<Integer>(9);Tree<Integer> t3 = new Node<Integer>(6,t1,t2);Tree<Integer> t4 = new Leaf<Integer>(7);Tree<Integer> t5 = new Node<Integer>(3,t3,t4);Tree<Integer> t6 = new Leaf<Integer>(4);Tree<Integer> t7 = new Leaf<Integer>(5);Tree<Integer> t8 = new Node<Integer>(2,t6,t7);return new Node<Integer>(1,t8,t5);

}

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.55

public class DfsTreeIterator<E> implements Iterator<E> {

private Iterator<E> iter;

public DfsTreeIterator(Tree<E> tree) {

List<E> list = new ArrayList<E>();

toList(tree,list);

iter = list.iterator();

}

public E next() {

return iter.next();

}

Iterators for Tree

© 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<E> tree, List<E> list) {

list.add(tree.getElement());

if (tree instanceof Node<?>) {

toList(((Node<E>) tree).getLeftSubTree(),list);

toList(((Node<E>) tree).getRightSubTree(),list);

}

}

}

© 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

2 3

4 5 6 7

9

1

2

3

45

6

7

8

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.58

public class BfsTreeIterator<E> implements Iterator<E> {

private Iterator<E> iter;

public BfsTreeIterator(Tree<E> tree) {

List<E> list = new ArrayList<E>();

LinkedList<Tree<E>> openList = new LinkedList<Tree<E>>();

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

2.59

public void remove() {

throw new UnsupportedOperationException();

}

private void toList(LinkedList<Tree<E>> openList,

List<E> list) {

while (!openList.isEmpty()) {

Tree<E> tree = openList.removeFirst();

list.add(tree.getElement());

if (tree instanceof Node<?>) {

openList.addLast(

((Node<E>) tree).getLeftSubTree());

openList.addLast(

((Node<E>) tree).getRightSubTree());

};

}

}

}

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.60

for(Iterator<Integer> it = new BfsTreeIterator<Integer>(tree);

it.hasNext(); )

System.out.print(it.next() + " ");

yields 1 2 3 4 5 6 7 8 9

8

1

2 3

4 5 6 7

9

1

2

3

4 5 6

7

8

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.62

Decorator - Structure

Operation()

Component

Operation()

ConcreteComponentcomponent

Operation()

Decorator

Operation() AddedBehavior();

ConcreteDecoratorB

addedState

ConcreteDecoratorA

Operation()

component.Operation();

super.Operation(); AddedBehavior();

© 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);

}

© 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) {…

}}

© 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);

}}

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

}

}

© 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);

}

}

© 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

© 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)

© 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 TextManipulator

return text.getExtent()

text

© 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 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

COSC 3P91 – Advanced Object-Oriented Programming

2.72

Class Adapter

Target

request()

Client

Adapter

request()

Adaptee

specificRequest()

specificRequest()

(implementation)

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.73

Object Adapter

Target

request()

Client

Adapter

request()

Adaptee

specificRequest()

adaptee.specificRequest()

adaptee

© 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.

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.75

Façade Motivation

Façade

subsystem classes

client classes

© 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

Scanner Token

© 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

© 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

© 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

© 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

© 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.

© 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

© 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;

}}

© 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.85

Null object - Structure

Delegator

OperationIF

NullOperation RealOperation

1

1

uses

Application

WarningRouter

routeWarning(:String)

IgnoreWarning

WarningDialog

1

1

uses

WarningLogger

Example

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

2.86

Null object - Examplepublic 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) {}

}

Recommended