Download presentation
Presentation is loading. Please wait.
Published byMonique Bromwell Modified over 9 years ago
1
CS490T Advanced Tablet Platform Applications Design Patterns
2
Introduction to Patterns They are reusable design solutions to reoccurring problems. They are reusable design solutions to reoccurring problems. Modeled after Architectural design Modeled after Architectural design Patterns have been called the next best software improvement since object-oriented programming. Patterns have been called the next best software improvement since object-oriented programming. Introduced in the book “Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides [GoF95] Introduced in the book “Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides [GoF95]
3
Introduction to Patterns Modeled after the books: “A pattern language: Towns, Buildings, Construction” by architect Christopher Alexander. Modeled after the books: “A pattern language: Towns, Buildings, Construction” by architect Christopher Alexander. Examples: Examples: –Symmetry is good –Use half-round arches to support bridges and in doors. Same equivalent ideas exist in software design Same equivalent ideas exist in software design
4
Parts of a Software Pattern Pattern Name Pattern Name Synopsis – One to two sentence description. Synopsis – One to two sentence description. Context – Describes the problem the pattern addresses. Context – Describes the problem the pattern 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 programming the solution Implementation – What to consider when programming the solution Related Patterns Related Patterns
5
Delegation (When not to Use Inheritance) [Grand98] Synopsis: Delegation is a way to extend a class without using inheritance. Synopsis: Delegation is a way to extend a class without using inheritance. Context: Inheritance can be used to extend a class but it forces “is-a-kind-of” relation. Context: Inheritance can be used to extend a class but it forces “is-a-kind-of” relation. –A person can be a teacher, student, administrator or a combination of them. –We cannot make a teacher a subclass of person since a teacher can also be a student. –We need something else to define the “is-a-role-played by” relation instead of inheritance.
6
Delegation (When not to Use Inheritance) [Grand98] (cont) Forces: Forces: –If an object is created as an instance of a class it will always be an instance of that class/super class. –If you find that a class attempts to hide a method inherited from another class, then it should not inherit from that class. Solution: Solution: –Use delegation. –Write a class that incorporates the functionality of the original class by using an instance of the original class and calling its methods.
7
Delegation (When not to Use Inheritance) [Grand98] (cont) Consequences: Consequences: –Less structured than inheritance Implementation: Implementation: –Obtain a reference of the class to which you want to delegate and call the methods. Code Example: Code Example: class Person { string name(); }; class Teacher { Person me; string name() { return me.name(); } };
8
Immutable [Grand98] Synopsis: Forbid modifying an object after it has been constructed. Synopsis: Forbid modifying an object after it has been constructed. Context: Situations when multiple objects use an instance of a class that does not need to be modified. Context: Situations when multiple objects use an instance of a class that does not need to be modified. Forces: Forces: –Your program uses instances of a class that are constant during the execution of the program. –An instance of an object that nevwer changes is used by multiple threads.
9
Immutable [Grand98] Solution: Build an immutable class by not providing in the interface methods that may modify the object. Solution: Build an immutable class by not providing in the interface methods that may modify the object. Consequences: It makes the code more robust. It solves problems of concurrency Consequences: It makes the code more robust. It solves problems of concurrency Implementation: Once the constructor builds the object, there are not methods that can modify it. Implementation: Once the constructor builds the object, there are not methods that can modify it.
10
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; } }
11
Proxy Synopsis: Forces method calls to an object to occur through a proxy object. Synopsis: Forces method calls to an object to occur through a proxy object. Context: Context: –A proxy may give the illusion that the object is local when it is in a different machine (remote-proxy). –A proxy controls access (access proxy). –Proxy acts as a logger object. –Proxy may act as a cache. Forces: Forces: –We want to add functionality that is orthogonal to the object itself.
12
Proxy Solution: Both proxy and service-providing object can inherit from a common class or implement a common interface. Solution: Both proxy and service-providing object can inherit from a common class or implement a common interface. Consequences: Service-providing object is used transparent to the object and to the users of the object. Consequences: Service-providing object is used transparent to the object and to the users of the object.
13
Proxy 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 ); }
14
Factory Method [GoF95] Synopsis: You want a class that can instantiate objects of arbitrary data types without being dependent of the classes it instantiates. Synopsis: You want a class that can instantiate objects of arbitrary data types without being dependent of the classes it instantiates. Context: Context: –Consider a graphical editor that can generate different shape objects. The shape objects may respond to common methods like paint(), resize(), move() etc. Forces Forces –To be reusable a factory class must create objects without knowing how they are implemented. –The set of classes the factory can instantiate may grow dynamically.
15
Factory Method [GoF95] Solution: Create a factory class that can create an object of different type. Provide a method to register new classes. Solution: Create a factory class that can create an object of different type. Provide a method to register new classes. Consequences: Consequences: –The factory class is independent of the objects instantiated. –The classes instantiated mya grow dynamically.
16
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); }
17
Iterator [GoF95] Synopsis: Synopsis: –Define an interface for sequentially accessing the objects in a collection. A class that access the collection will remain independent of the collection. Context: Context: –Imagine obtaining the inventory of a warehouse. The inventory browsing classes must be independent of the collections classes. –The browsing classes may be used for different collections that provide the same iterator interface.
18
Iterator Iterator [GoF95] Forces Forces –A class needs to access the contents of a collection without becoming dependent on the collection. Solution Solution –Define the iterator interface that collections will define. Have the collection create an iterator object used to browse collection.
19
Iterator [GoF95] Implementation: public interface InventoryIteratorIF { public interface InventoryIteratorIF { 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 collection classes. Consequences: Decouple browsing classes from collection classes.
20
Virtual Proxy [Larman98] Synopsis: Synopsis: –An object that is expensive to instantiate may have its initialization delayed until it is required. Context: Context: –Imagine that an application needs to read tables from a file. Instead of reading the tables at initialization, they will be read until they are required.
21
Virtual Proxy [Larman98] Forces: Forces: –It may be time consuming to instantiate class and in some cases it may not be needed. –Improve startup times. Solution: Solution: –Create object but do not initialize it. Initialize object the first time it is used.
22
Virtual Proxy [Larman98] Implementation: Implementation: 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. –It may cause delay during the first operation.
23
Command [GoF95] Synopsis: Synopsis: –Encapsulate commands in objects so you can control selection and sequencing, queue them, undo them and manipulate them. Context: Context: –Imagine you want to design a graphic editor and you want to undo/redo commands. –You may have each command be an object that provides a do() and undo() methods. –The commands will be stored in a queue. To undo one command execute undo() in last command. Alternatively clean and do all the commands except last one.
24
Command [GoF95] Forces: Forces: –We need undo/redo management. –Sequence of commands can be stored for future testing. Solution: Solution: –Create abstract interface with do() and undo() methods. Have command objects implement abstract interface. Have a command manager object store commands in queue and performed do/redo operations.
25
Command [GoF95] Implementation: Implementation: 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 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); }}
26
Command [GoF95] Consequences: Consequences: –Flexibility in sequencing of commands. –Allow to replay commands at any time.
27
Observer [ GoF95] Synopsis: Synopsis: –Allow to dynamically register dependencies between objects, so that an object will notify those objects that are dependent on it when its state changes. Context: Context: –You have a directory viewing program that shows the contents of the directory. The program registers a “Listener” in the directory object to be notified of changes in the directory.
28
Observer [GoF95] Forces: Forces: –An instance of one class needs to notify the instance of another class that the state changed. –You may have a one-to-many dependency that may require one object top notify multiple objects. Solution: Solution: –Implement a Listener abstract class. The observer object implements this interface and registers itself as a listener in the observable object. –The observer object is notified when the state changes.
29
Observer [GoF95] Implementation Implementation interface DirChangeListener { void contentChanged(Directory d) } Class DirectoryBrowser implements DirChangeListener {......} Class Directory { public registerListener( DirChangeListener l ); …} Consequences: Consequences: –Cyclic dependencies may arise
30
Visitor [GoF 95] Synopsis: Synopsis: -When you need to do operations in a complex structure, you can separate the operation from the structure by using a visitor class. - Context: -Suppose you want the ability of creating a table of contents in a word processor. -The word processor may allow a way to iterate over all the paragraphs and document structures by calling a visitor object. -You may write a visitor object that extracts the titles necessary for the table of contents.
31
Visitor [GoF95] Forces: Forces: –There are a variety of operations that need to be performed to an object structure. –The object structure is composed of objects that belong to different classes. Solution: Solution: –Implement an abstract class Visitor that he concrete visitor implements and that has multiple visit methods for different types of objects. –The ObjectStructure implements a visit method that takes a Visitor object as argument. –The methods in theVisitor object is called by the visit method of the ObjectStructure for every object in the structure.
32
Visitor [GoF95] Implementation Implementation Interface WordProcessorVisitor { void visit(Paragraph p); void visit(Title t); } public class WordProcessor { …. public visit(WordProcessorVisitor v) {…} } Public class CreateTOC implements WordProcessorVisitor { void visit(Paragraph p) {…} void visit(Paragraph p) {…} void visit(Title t) {…} }
33
Read/Write Lock [Lea 97] Synopsis: Synopsis: –Allow concurrent read access to an object but require exclusive access for write operations. Context Context –Imagine you want to build an auction site. –Users want to see the current bid of an item. –Users make bids for items. –Highest bidder takes the item.
34
Read/Write Lock [Lea 97] Forces: Forces: –Read operations are more frequent than write operations. –Exclusive access is necessary for write operations. Solution: Solution: –Use a read/write lock that allows concurrent access to the read bids but exclusive access to do bids.
35
Read/Write Lock [Lea 97] Implementation Implementation –Use pthread_rwlock Consequences Consequences –Starvation may occur
36
Bibliography [GoF95]Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. “Design Patterns: Elements of Reusable Object- Oriented Software”. Reading Mass. Addison Wesley, 1995. [GoF95]Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. “Design Patterns: Elements of Reusable Object- Oriented Software”. Reading Mass. Addison Wesley, 1995. [Grand98] Mark Grand. “Patterns in Java. A Catalog of Reusable Design Patterns in Java Illustrated with UML.” Wiley 1998. [Grand98] Mark Grand. “Patterns in Java. A Catalog of Reusable Design Patterns in Java Illustrated with UML.” Wiley 1998.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.