DOC PREVIEW
UMD CMSC 132 - Design Patterns II

This preview shows page 1-2-22-23 out of 23 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1CMSC 132: Object-Oriented Programming IIDesign Patterns IIDepartment of Computer ScienceUniversity of Maryland, College Park2More Design PatternsMarker interfaceLabel semantic attributes of a classObserverA way of notifying change to a number of classesStateAlter an object's behavior when its state changesVisitorDefines a new operation to a class without changing class3Marker Interface PatternDefinitionLabel semantic attributes of a classWhere to use & benefitsNeed to indicate attribute(s) of a classAllows identification of attributes of objects without assuming they are instances of any particular class4Marker Interface PatternExampleClasses with desirable property GoodPropertyOriginalStore flag for GoodProperty in each class Using patternLabel class using GoodProperty interfaceExamples from JavaCloneableSerializable5Marker Interface Examplepublic interface GoodProperty { } // no methodsclass A implements GoodProperty { … }class B { … }class A goodObj = new A();class B badObj = new B();if (goodObj instanceof GoodProperty) … // Trueif (badObj instanceof GoodProperty) … // False6Observer PatternDefinitionUpdates all dependents of object automatically once object changes stateWhere to use & benefitsOne change affects one or many objectsMany object behavior depends on one object stateNeed broadcast communicationMaintain consistency between objectsObservers do not need to constantly check for changes7Observer PatternExampleMultiple windows (views) for single documentOriginalEach window checks documentWindow updates image if document changesUsing patternEach window registers as observer for documentDocument notifies all of its observers when it changesDocWindowDocWindowWindowWindow8Observer Examplepublic interface Observer {public void update(Observable o, Object a) // called when observed object o changes}public class Observable {protected void setChanged() // changedprotected void clearChanged() // no changeboolean hasChanged() // return changed?void addObserver(Observer o) // track observersvoid notifyObservers() // notify if changed,void notifyObservers(Object a) // then clear change}9Observer Examplepublic class MyWindow implements Observer {public openDoc(Observable doc) {doc.addObservers(this); // add window to list}public void update(Observable doc, Object arg) {redraw(doc); // display updated document}}public class MyDoc extends Observable {public void edit() {… // edit documentsetChanged(); // mark changenotifyObservers(arg); // invokes update()}}10State PatternDefinitionRepresent change in an object’s behavior using its member classesWhere to use & benefitsControl states without many if-else statementsRepresent states using classesEvery state has to act in a similar mannerSimplify and clarify the program11State PatternExampleStates representing finite state machine (FSM)OriginalEach method chooses action depending on stateBehavior may be confusing, state is implicit Using patternState interface defines list of actions for state Define inner classes implementing State interfaceFinite state machine instantiates each state and tracks its current stateCurrent state used to choose action12State Example – Original Code public class FickleFruitVendor {boolean wearingHat;boolean isHatOn() { return wearingHat; }String requestFruit() {if (wearingHat) {wearingHat = false;return "Banana";}else {wearingHat = true;return "Apple";}}}WearingHatNotWearingHatBananaApple13State Examplepublic interface State {boolean isHatOn();String requestFruit();}public class WearingHat implements State;public class NotWearingHat implements State;14State Examplepublic class FickleFruitVendor {State wearingHat = new WearingHat();State notWearingHat = new NotWearingHat();// explicitly track current state of VendorState currentState = wearingHat;// behavior of Vendor depends on current statepublic boolean isHatOn() {return currentState.isHatOn();}public String requestFruit() {return currentState.requestFruit();}15State Exampleclass WearingHat implements State {boolean isHatOn() { return true; }String requestFruit() {currentState = notWearingHat; // change statereturn "Banana";}}class NotWearingHat implements State {boolean isHatOn() { return false; }String requestFruit() {currentState = wearingHat; // change statereturn "Apple";}}} // end class WearingHatNotWearingHatBananaApple16Visitor PatternDefinitionDefine operations on elements of data structures without changing their classesWhere to use & benefitsAdd operations to classes with different interfacesCan modify operations on data structure easily Encapsulate operations on elements of data structureDecouples classes for data structure and algorithms Crossing class hierarchies may break encapsulation17Visitor PatternExamplePrint elements in collection of objectsOriginalIterator chooses action based on type of objectMany if-else statements Using patternVisitor interface defines actions during visitVisitable interface allow objects to accept visitAction automatically selected by polymorphic functions through double dispatch18Visitor Example – Original Codepublic void messyPrintCollection(Collection c) {for (Object o : c) {if (o instanceof String)System.out.println(“{"+o.toString()+“}"); // add { }else if (o instanceof Float)System.out.println(o.toString()+"f"); // add felseSystem.out.println(o.toString());}}19Visitor Examplepublic interface Visitor{public void visit(VisitableString s);public void visit(VisitableFloat f);}public interface Visitable{public void accept(Visitor v);}20Visitor Examplepublic class VisitableString implements Visitable{private String value;public VisitableString(String s) { value = s; }public String toString( ) { return value.toString( ); }public void accept(Visitor v) { v.visit(this); }}public class VisitableFloat implements Visitable{private Float value;public VisitableFloat(Float f) { value = f; }public String toString( ) { return value.toString( ); }public void accept(Visitor v) { v.visit(this); }}Double dispatch21Visitor Examplepublic class PrintVisitor implements Visitor{public void visitCollection(Collection c) {for (Object o : c) {if (o instanceof Visitable)((Visitable) o).accept(this);elseSystem.out.println(o.toString());} }public void visit(VisitableString s) {System.out.println(“{"+s.toString( )+“}");}public void visit (VisitableFloat f) {System.out.println(f.toString( )+"f");} }22UML Class Diagram of Abstract Visitor23Design Patterns – SummaryCan be useful for designing quality


View Full Document

UMD CMSC 132 - Design Patterns II

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download Design Patterns II
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Design Patterns II and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Design Patterns II 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?