cs490t advanced tablet platform applications design patterns

36
CS490T Advanced Tablet Platform CS490T Advanced Tablet Platform Applications Applications Design Patterns Design Patterns

Upload: monique-bromwell

Post on 15-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS490T Advanced Tablet Platform Applications Design Patterns

CS490T Advanced Tablet Platform CS490T Advanced Tablet Platform ApplicationsApplications

Design PatternsDesign Patterns

Page 2: CS490T Advanced Tablet Platform Applications Design Patterns

Introduction to PatternsIntroduction to Patterns

They are reusable design solutions to reoccurring They are reusable design solutions to reoccurring problems.problems.

Modeled after Architectural designModeled after Architectural design Patterns have been called the next best software Patterns have been called the next best software

improvement since object-oriented programming.improvement since object-oriented programming. Introduced in the book “Design Patterns: Elements Introduced in the book “Design Patterns: Elements

of Reusable Object-Oriented Software by Gamma, of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides [GoF95]Helm, Johnson and Vlissides [GoF95]

Page 3: CS490T Advanced Tablet Platform Applications Design Patterns

Introduction to PatternsIntroduction to Patterns

Modeled after the books: “A pattern Modeled after the books: “A pattern language: Towns, Buildings, Construction” language: Towns, Buildings, Construction” by architect Christopher Alexander.by architect Christopher Alexander.

Examples:Examples:– Symmetry is goodSymmetry is good– Use half-round arches to support bridges and in Use half-round arches to support bridges and in

doors.doors. Same equivalent ideas exist in software Same equivalent ideas exist in software

designdesign

Page 4: CS490T Advanced Tablet Platform Applications Design Patterns

Parts of a Software PatternParts of a Software Pattern

Pattern NamePattern Name Synopsis – One to two sentence description.Synopsis – One to two sentence description. Context – Describes the problem the pattern Context – Describes the problem the pattern

addresses.addresses. Forces – What leads to the solution proposed.Forces – What leads to the solution proposed. Solution – Describes the general solution.Solution – Describes the general solution. Consequences – Implications good and bad.Consequences – Implications good and bad. Implementation – What to consider when Implementation – What to consider when

programming the solutionprogramming the solution Related Patterns Related Patterns

Page 5: CS490T Advanced Tablet Platform Applications Design Patterns

Delegation (When not to Use Delegation (When not to Use Inheritance) [Grand98]Inheritance) [Grand98]

Synopsis: Delegation is a way to extend a class Synopsis: Delegation is a way to extend a class without using inheritance.without using inheritance.

Context: Inheritance can be used to extend a class Context: Inheritance can be used to extend a class but it forces “is-a-kind-of” relation.but it forces “is-a-kind-of” relation.– A person can be a teacher, student, administrator or a A person can be a teacher, student, administrator or a

combination of them.combination of them.

– We cannot make a teacher a subclass of person since a We cannot make a teacher a subclass of person since a teacher can also be a student.teacher can also be a student.

– We need something else to define the “is-a-role-played We need something else to define the “is-a-role-played by” relation instead of inheritance.by” relation instead of inheritance.

Page 6: CS490T Advanced Tablet Platform Applications Design Patterns

Delegation (When not to Use Delegation (When not to Use Inheritance) [Grand98] (cont)Inheritance) [Grand98] (cont)

Forces:Forces:– If an object is created as an instance of a class it will If an object is created as an instance of a class it will

always be an instance of that class/super class.always be an instance of that class/super class.– If you find that a class attempts to hide a method If you find that a class attempts to hide a method

inherited from another class, then it should not inherit inherited from another class, then it should not inherit from that class.from that class.

Solution: Solution: – Use delegation. Use delegation. – Write a class that incorporates the functionality of the Write a class that incorporates the functionality of the

original class by using an instance of the original class original class by using an instance of the original class and calling its methods. and calling its methods.

Page 7: CS490T Advanced Tablet Platform Applications Design Patterns

Delegation Delegation (When not to Use (When not to Use Inheritance) [Grand98] (cont)Inheritance) [Grand98] (cont)

Consequences:Consequences:– Less structured than inheritanceLess structured than inheritance

Implementation:Implementation:– Obtain a reference of the class to which you Obtain a reference of the class to which you

want to delegate and call the methods.want to delegate and call the methods. Code Example:Code Example: class Person {

string name();

};

class Teacher {

Person me;

string name() { return me.name(); }

};

Page 8: CS490T Advanced Tablet Platform Applications Design Patterns

Immutable [Grand98]Immutable [Grand98]

Synopsis: Forbid modifying an object after it has Synopsis: Forbid modifying an object after it has been constructed.been constructed.

Context: Situations when multiple objects use an Context: Situations when multiple objects use an instance of a class that does not need to be instance of a class that does not need to be modified. modified.

Forces: Forces: – Your program uses instances of a class that are constant Your program uses instances of a class that are constant

during the execution of the program.during the execution of the program.

– An instance of an object that nevwer changes is used by An instance of an object that nevwer changes is used by multiple threads.multiple threads.

Page 9: CS490T Advanced Tablet Platform Applications Design Patterns

Immutable [Grand98]Immutable [Grand98]

Solution: Build an immutable class by not Solution: Build an immutable class by not providing in the interface methods that may providing in the interface methods that may modify the object.modify the object.

Consequences: It makes the code more Consequences: It makes the code more robust. It solves problems of concurrencyrobust. It solves problems of concurrency

Implementation: Once the constructor Implementation: Once the constructor builds the object, there are not methods that builds the object, there are not methods that can modify it.can modify it.

Page 10: CS490T Advanced Tablet Platform Applications Design Patterns

Immutable [Grand98]Immutable [Grand98]

Code Example:Code Example:Class Position {

private int x;

private int y;

public Position( int x, int y ) {

this.x = x;

this.y= y;

}

public int getX() { return x; }

public int getY() {return y; }

}

Page 11: CS490T Advanced Tablet Platform Applications Design Patterns

ProxyProxy

Synopsis: Forces method calls to an object to Synopsis: Forces method calls to an object to occur through a proxy object.occur through a proxy object.

Context: Context: – A proxy may give the illusion that the object is local A proxy may give the illusion that the object is local

when it is in a different machine (remote-proxy). when it is in a different machine (remote-proxy). – A proxy controls access (access proxy).A proxy controls access (access proxy).– Proxy acts as a logger object.Proxy acts as a logger object.– Proxy may act as a cache.Proxy may act as a cache.

Forces: Forces: – We want to add functionality that is orthogonal to the We want to add functionality that is orthogonal to the

object itself.object itself.

Page 12: CS490T Advanced Tablet Platform Applications Design Patterns

ProxyProxy

Solution: Both proxy and service-providing Solution: Both proxy and service-providing object can inherit from a common class or object can inherit from a common class or implement a common interface.implement a common interface.

Consequences: Service-providing object is Consequences: Service-providing object is used transparent to the object and to the used transparent to the object and to the users of the object.users of the object.

Page 13: CS490T Advanced Tablet Platform Applications Design Patterns

ProxyProxy Implementation/Code Example:Implementation/Code Example:

interface Table {

void add( string key, void * item);

}

class MyTable: implements Table {

void add( string key, void * item);

}

class TableLogger implements Table {

Table mytable;

TableProxy( Table t ) { mytable = t; }

void add (string key, void * item) {

log( “add”, key, item );

mytable.add( key, item );

}

}

Page 14: CS490T Advanced Tablet Platform Applications Design Patterns

Factory Method [GoF95]Factory Method [GoF95]

Synopsis: You want a class that can instantiate Synopsis: You want a class that can instantiate objects of arbitrary data types without being objects of arbitrary data types without being dependent of the classes it instantiates.dependent of the classes it instantiates.

Context: Context: – Consider a graphical editor that can generate different Consider a graphical editor that can generate different

shape objects. The shape objects may respond to common shape objects. The shape objects may respond to common methods like paint(), resize(), move() etc.methods like paint(), resize(), move() etc.

ForcesForces– To be reusable a factory class must create objects without To be reusable a factory class must create objects without

knowing how they are implemented.knowing how they are implemented.– The set of classes the factory can instantiate may grow The set of classes the factory can instantiate may grow

dynamically.dynamically.

Page 15: CS490T Advanced Tablet Platform Applications Design Patterns

Factory Method [GoF95]Factory Method [GoF95]

Solution: Create a factory class that can Solution: Create a factory class that can create an object of different type. Provide a create an object of different type. Provide a method to register new classes.method to register new classes.

Consequences:Consequences:– The factory class is independent of the objects The factory class is independent of the objects

instantiated.instantiated.– The classes instantiated mya grow dynamically.The classes instantiated mya grow dynamically.

Page 16: CS490T Advanced Tablet Platform Applications Design Patterns

Factory Method [GoF95]Factory Method [GoF95] Implementation/Code Example:Implementation/Code Example:

interface Shape {

void paint();

void move( Position pos );

static Shape newShape( Position pos, Dimension dim);

}

class ShapeFactory{

Shape newShape( string shapeName );

void register( string shapeName, Shape initialShape);

}

Page 17: CS490T Advanced Tablet Platform Applications Design Patterns

Iterator [GoF95] Iterator [GoF95]

Synopsis: Synopsis: – Define an interface for sequentially accessing the Define an interface for sequentially accessing the

objects in a collection. A class that access the collection objects in a collection. A class that access the collection will remain independent of the collection.will remain independent of the collection.

Context: Context: – Imagine obtaining the inventory of a warehouse. The Imagine obtaining the inventory of a warehouse. The

inventory browsing classes must be independent of the inventory browsing classes must be independent of the collections classes.collections classes.

– The browsing classes may be used for different The browsing classes may be used for different collections that provide the same iterator interface.collections that provide the same iterator interface.

Page 18: CS490T Advanced Tablet Platform Applications Design Patterns

Iterator Iterator [GoF95] Iterator Iterator [GoF95]

ForcesForces– A class needs to access the contents of a A class needs to access the contents of a

collection without becoming dependent on the collection without becoming dependent on the collection.collection.

SolutionSolution– Define the iterator interface that collections will Define the iterator interface that collections will

define. Have the collection create an iterator define. Have the collection create an iterator object used to browse collection.object used to browse collection.

Page 19: CS490T Advanced Tablet Platform Applications Design Patterns

Iterator [GoF95]Iterator [GoF95]

Implementation:Implementation: public interface InventoryIteratorIF {public interface InventoryIteratorIF {

public InventoryItem getNext();public InventoryItem getNext();

}}

public class InventoryCollection {public class InventoryCollection {

public InventoryIteratorIF iterator()public InventoryIteratorIF iterator()

return new InventoryIterator();return new InventoryIterator();

}}

}}

Consequences: Decouple browsing classes from Consequences: Decouple browsing classes from collection classes.collection classes.

Page 20: CS490T Advanced Tablet Platform Applications Design Patterns

Virtual Proxy [Larman98]Virtual Proxy [Larman98]

Synopsis: Synopsis: – An object that is expensive to instantiate may An object that is expensive to instantiate may

have its initialization delayed until it is have its initialization delayed until it is required.required.

Context:Context:– Imagine that an application needs to read tables Imagine that an application needs to read tables

from a file. Instead of reading the tables at from a file. Instead of reading the tables at initialization, they will be read until they are initialization, they will be read until they are required.required.

Page 21: CS490T Advanced Tablet Platform Applications Design Patterns

Virtual Proxy [Larman98]Virtual Proxy [Larman98]

Forces:Forces:– It may be time consuming to instantiate class It may be time consuming to instantiate class

and in some cases it may not be needed.and in some cases it may not be needed.– Improve startup times.Improve startup times.

Solution:Solution:– Create object but do not initialize it. Initialize Create object but do not initialize it. Initialize

object the first time it is used.object the first time it is used.

Page 22: CS490T Advanced Tablet Platform Applications Design Patterns

Virtual Proxy [Larman98]Virtual Proxy [Larman98]

Implementation:Implementation:Class LazyTable {Class LazyTable { private table = null;private table = null; public Object lookup() {public Object lookup() { if ( table == null) table = new Table;if ( table == null) table = new Table; return table.lookup;return table.lookup; }}}}

Consequences: Consequences: – Delay object creation until needed. Delay object creation until needed. – It may cause delay during the first operation.It may cause delay during the first operation.

Page 23: CS490T Advanced Tablet Platform Applications Design Patterns

Command [GoF95]Command [GoF95] Synopsis:Synopsis:

– Encapsulate commands in objects so you can control Encapsulate commands in objects so you can control selection and sequencing, queue them, undo them and selection and sequencing, queue them, undo them and manipulate them.manipulate them.

Context:Context:– Imagine you want to design a graphic editor and you Imagine you want to design a graphic editor and you

want to undo/redo commands.want to undo/redo commands.– You may have each command be an object that provides You may have each command be an object that provides

a do() and undo() methods.a do() and undo() methods.– The commands will be stored in a queue. To undo one The commands will be stored in a queue. To undo one

command execute undo() in last command. Alternatively command execute undo() in last command. Alternatively clean and do all the commands except last one. clean and do all the commands except last one.

Page 24: CS490T Advanced Tablet Platform Applications Design Patterns

Command [GoF95]Command [GoF95]

Forces:Forces:– We need undo/redo management.We need undo/redo management.– Sequence of commands can be stored for future Sequence of commands can be stored for future

testing.testing. Solution:Solution:

– Create abstract interface with do() and undo() Create abstract interface with do() and undo() methods. Have command objects implement methods. Have command objects implement abstract interface. Have a command manager abstract interface. Have a command manager object store commands in queue and performed object store commands in queue and performed do/redo operations.do/redo operations.

Page 25: CS490T Advanced Tablet Platform Applications Design Patterns

Command [GoF95]Command [GoF95]

Implementation:Implementation:public abstract class Command {public abstract class Command { public abstract boolean doIt();public abstract boolean doIt(); public abstract boolean undoIt();public abstract boolean undoIt();}}public abstract class CommandManager {public abstract class CommandManager { public void invokeCommand( Command c) {public void invokeCommand( Command c) {

if ( c instanceof Undo) undoLast();if ( c instanceof Undo) undoLast(); else if ( c instanceof Do) redoLast();else if ( c instanceof Do) redoLast();

else { c.doIt(); addToHistory( c);else { c.doIt(); addToHistory( c);}}

}}

Page 26: CS490T Advanced Tablet Platform Applications Design Patterns

Command [GoF95]Command [GoF95]

Consequences:Consequences:– Flexibility in sequencing of commands.Flexibility in sequencing of commands.– Allow to replay commands at any time.Allow to replay commands at any time.

Page 27: CS490T Advanced Tablet Platform Applications Design Patterns

Observer [ GoF95]Observer [ GoF95]

Synopsis: Synopsis: – Allow to dynamically register dependencies Allow to dynamically register dependencies

between objects, so that an object will notify between objects, so that an object will notify those objects that are dependent on it when its those objects that are dependent on it when its state changes.state changes.

Context: Context: – You have a directory viewing program that You have a directory viewing program that

shows the contents of the directory. The shows the contents of the directory. The program registers a “Listener” in the directory program registers a “Listener” in the directory object to be notified of changes in the directory.object to be notified of changes in the directory.

Page 28: CS490T Advanced Tablet Platform Applications Design Patterns

Observer [GoF95]Observer [GoF95]

Forces:Forces:– An instance of one class needs to notify the instance of An instance of one class needs to notify the instance of

another class that the state changed.another class that the state changed.

– You may have a one-to-many dependency that may You may have a one-to-many dependency that may require one object top notify multiple objects.require one object top notify multiple objects.

Solution:Solution:– Implement a Listener abstract class. The observer Implement a Listener abstract class. The observer

object implements this interface and registers itself as a object implements this interface and registers itself as a listener in the observable object. listener in the observable object.

– The observer object is notified when the state changes.The observer object is notified when the state changes.

Page 29: CS490T Advanced Tablet Platform Applications Design Patterns

Observer [GoF95]Observer [GoF95]

ImplementationImplementationinterface DirChangeListener {interface DirChangeListener {

void contentChanged(Directory d)void contentChanged(Directory d)}}Class DirectoryBrowser Class DirectoryBrowser

implements DirChangeListener {implements DirChangeListener { . . .. . .} } Class Directory {Class Directory {

public registerListener( DirChangeListener l );public registerListener( DirChangeListener l );……}}

Consequences:Consequences: – Cyclic dependencies may ariseCyclic dependencies may arise

Page 30: CS490T Advanced Tablet Platform Applications Design Patterns

Visitor [GoF 95]Visitor [GoF 95]

Synopsis:Synopsis:- When you need to do operations in a complex structure, When you need to do operations in a complex structure,

you can separate the operation from the structure by you can separate the operation from the structure by using a visitor class.using a visitor class.

- Context:Context:- Suppose you want the ability of creating a table of Suppose you want the ability of creating a table of

contents in a word processor. contents in a word processor. - The word processor may allow a way to iterate over all The word processor may allow a way to iterate over all

the paragraphs and document structures by calling a the paragraphs and document structures by calling a visitor object.visitor object.

- You may write a visitor object that extracts the titles You may write a visitor object that extracts the titles necessary for the table of contents.necessary for the table of contents.

Page 31: CS490T Advanced Tablet Platform Applications Design Patterns

Visitor [GoF95]Visitor [GoF95]

Forces:Forces:– There are a variety of operations that need to be performed to There are a variety of operations that need to be performed to

an object structure.an object structure.– The object structure is composed of objects that belong to The object structure is composed of objects that belong to

different classes.different classes. Solution:Solution:

– Implement an abstract class Visitor that he concrete visitor Implement an abstract class Visitor that he concrete visitor implements and that has multiple visit methods for different implements and that has multiple visit methods for different types of objects.types of objects.

– The ObjectStructure implements a visit method that takes a The ObjectStructure implements a visit method that takes a Visitor object as argument.Visitor object as argument.

– The methods in theVisitor object is called by the visit method The methods in theVisitor object is called by the visit method of the ObjectStructure for every object in the structure.of the ObjectStructure for every object in the structure.

Page 32: CS490T Advanced Tablet Platform Applications Design Patterns

Visitor [GoF95]Visitor [GoF95]

ImplementationImplementationInterface WordProcessorVisitor {Interface WordProcessorVisitor {

void visit(Paragraph p);void visit(Paragraph p);void visit(Title t);void visit(Title t);

}}public class WordProcessor {public class WordProcessor {

……..public visit(WordProcessorVisitor v) {…}public visit(WordProcessorVisitor v) {…}

}}Public class CreateTOC implements WordProcessorVisitor {Public class CreateTOC implements WordProcessorVisitor { void visit(Paragraph p) {…}void visit(Paragraph p) {…}

void visit(Title t) {…}void visit(Title t) {…}}}

Page 33: CS490T Advanced Tablet Platform Applications Design Patterns

Read/Write Lock [Lea 97]Read/Write Lock [Lea 97]

Synopsis:Synopsis:– Allow concurrent read access to an object but Allow concurrent read access to an object but

require exclusive access for write operations.require exclusive access for write operations. ContextContext

– Imagine you want to build an auction site. Imagine you want to build an auction site. – Users want to see the current bid of an item. Users want to see the current bid of an item. – Users make bids for items.Users make bids for items.– Highest bidder takes the item.Highest bidder takes the item.

Page 34: CS490T Advanced Tablet Platform Applications Design Patterns

Read/Write Lock [Lea 97]Read/Write Lock [Lea 97]

Forces:Forces:– Read operations are more frequent than write Read operations are more frequent than write

operations.operations.– Exclusive access is necessary for write Exclusive access is necessary for write

operations.operations. Solution:Solution:

– Use a read/write lock that allows concurrent Use a read/write lock that allows concurrent access to the read bids but exclusive access to access to the read bids but exclusive access to do bids.do bids.

Page 35: CS490T Advanced Tablet Platform Applications Design Patterns

Read/Write Lock [Lea 97]Read/Write Lock [Lea 97]

ImplementationImplementation– Use pthread_rwlockUse pthread_rwlock

ConsequencesConsequences– Starvation may occurStarvation may occur

Page 36: CS490T Advanced Tablet Platform Applications Design Patterns

BibliographyBibliography

[GoF95]Erich Gamma, Richard Helm, [GoF95]Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. “Design Ralph Johnson, and John Vlissides. “Design Patterns: Elements of Reusable Object-Patterns: Elements of Reusable Object-Oriented Software”. Reading Mass. Oriented Software”. Reading Mass. Addison Wesley, 1995.Addison Wesley, 1995.

[Grand98] Mark Grand. “Patterns in Java. A [Grand98] Mark Grand. “Patterns in Java. A Catalog of Reusable Design Patterns in Java Catalog of Reusable Design Patterns in Java Illustrated with UML.” Wiley 1998.Illustrated with UML.” Wiley 1998.