DOC PREVIEW
UMD CMSC 132 - Design Patterns 2

This preview shows page 1-2-3-4 out of 12 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 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 12 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 12 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 12 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Design Patterns 2Nelson Padua-PerezChau-Wen TsengDepartment of Computer ScienceUniversity of Maryland, College ParkMore 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 class2Marker 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 classMarker Interface PatternExampleClasses with desirable property GoodPropertyOriginalStore flag for GoodProperty in each class Using patternLabel class using GoodProperty interfaceExamples from JavaCloneableSerializable3Marker 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) … // FalseObserver 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 changes4Observer 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 changesDocWindowDocWindowWindowWindowObserver Examplepublic interface Observer {public void update(Observable o, Object a) // called when observed object o changes}public class Observable extends Object {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}5Observer 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()}}State 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 program6State 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 action State 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";}}}WearingHatNotWearingHatBananaApple7State Examplepublic interface State {boolean isHatOn();String requestFruit();}public class WearingHat implements State;public class NotWearingHat implements State;State 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();}8State 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 WearingHatNotWearingHatBananaAppleVisitor 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 encapsulation9Visitor 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 dispatchVisitor Example – Original Codepublic void messyPrintCollection(Collection c) {Iterator iterator = c.iterator()while (iterator.hasNext()) {Object o = iterator.next();if (o instanceof Collection)messyPrintCollection((Collection)o);else 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());}}10Visitor Examplepublic interface Visitor{public void visitCollection(Collection c);public void visitString(String string);public void visitFloat(Float float);}public interface Visitable{public void accept(Visitor v);}Visitor Examplepublic class VisitableString implements Visitable{private String value;public VisitableString(String s) { value = s; }public void accept(Visitor v) { v.visitString(this); }}public class VisitableFloat implements Visitable{private Float value;public VisitableFloat(Float f) { value = f; }public void accept(Visitor v) { v.visitFloat(this); }}Double dispatch11Visitor Examplepublic class PrintVisitor implements Visitor{public void visitCollection(Collection c) {Iterator iterator = c.iterator()while (iterator.hasNext()) {Object o = iterator.next();if (o instanceof Visitable)((Visitable) o).accept(this);}public void visitString(String s) {System.out.println("'"+s+"'");}public void visitFloat(Float f) {System.out.println(f.toString()+"f");}}UML Class Diagram of Abstract


View Full Document

UMD CMSC 132 - Design Patterns 2

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