Presentation is loading. Please wait.

Presentation is loading. Please wait.

Design Patterns, conclusion

Similar presentations


Presentation on theme: "Design Patterns, conclusion"— Presentation transcript:

1 Design Patterns, conclusion

2 So Far: Creational Patterns
Factories, Prototype, Singleton, Interning Problem: constructors in Java (and other OO languages) are inflexible 1. Can’t return a subtype of the type they belong to. “Factory” patterns address the issue: Factory method (e.g. createBicycle()), Factory class/object, Prototype 2. Always return a fresh new object, can’t reuse. “Sharing” patterns address the issue: Singleton, Interning Spring 18 CSCI 2600, K. Kuzmin, A Milanova

3 So Far: Structural Patterns
Wrappers: Adapter, Decorator, Proxy Adapter: changes interface, preserves functionality Decorator: preserves interface, changes functionality Proxy: typically preserves both interface and functionality Composite A structural pattern: build complex whole-part structures, give uniform interface to client Spring 18 CSCI 2600, K. Kuzmin, A Milanova

4 So Far: Behavioral Patterns
Traversal of composites: Interpreter, Procedural and Visitor Interpreter: groups code by object Procedural, Visitor: group code by operation Low (weak) coupling: Observer, Façade Observer: decouples data (model) from views Façade (actually, considered structural pattern): decouples client from complex library Spring 18 CSCI 2600, K. Kuzmin, A Milanova

5 Outline Behavioral patterns for traversing composites
Visitor, conclusion! Behavioral pattern for traversal of containers Iterator Design exercise More patterns: Strategy and Command, others Odds and ends on creating objects

6 Iterator Pattern Motivation: access the elements of a collection without exposing representation AbstractList Iterator iterator() equals() hasNext() next() LinkedList ArrayList LinkedListIterator ArrayListIterator iterator() iterator() hasNext() next() hasNext() next() Spring 18 CSCI 2600, K. Kuzmin, A Milanova creates

7 Iterator Pattern Visitor vs. Iterator?
Visitor pattern is similar to Iterator but different because it has knowledge of structure, not just sequence Spring 18 CSCI 2600, K. Kuzmin, A Milanova

8 Template Method Pattern
Motivation: factors out skeleton of algorithm, deferring some steps to subclasses AbstractList Iterator iterator() equals() hasNext() next() Which one is the template method here? Where else did we see template method? (Answer: createRace() in Bicycle Hierarchy.) LinkedList ArrayList LinkedListIterator ArrayListIterator iterator() iterator() hasNext() next() hasNext() next() Spring 18 CSCI 2600, K. Kuzmin, A Milanova creates

9 Design Patterns Summary so Far
Factory method, Factory object, Prototype Creational patterns: address problem that constructors can’t return subtypes Singleton, Interning Creational patterns: address problem that constructors always return a new instance of class Wrappers: Adapter, Decorator, Proxy Structural patterns: when we want to change interface or functionality of an existing class, or restrict access to an object Spring 18 CSCI 2600, K. Kuzmin, A Milanova

10 Design Patterns Summary so Far
Composite A structural pattern: expresses whole-part structures, gives uniform interface to client Interpreter, Procedural, Visitor Behavioral patterns: address the problem of how to traverse composite structures Iterator Template method

11 A Design Exercise We are building a document editor --- a large rectangle that displays a document. Document can mix text, graphical shapes, etc. Surrounding the document are the menu, scrollbars, borders, etc. Structure, Formatting, Embellishing the UI, User commands, Spell checking Spring 18 CSCI 2600, K. Kuzmin, A Milanova

12 Structure Hierarchical structure --- document is made of columns, a column is made up of rows, a row is made up of words, images, etc. Editor should treat text and graphics uniformly. Editor should treat simple and complex elements uniformly What design pattern? Spring 18 CSCI 2600, K. Kuzmin, A Milanova

13 The Composite Pattern 1 Glyph Editor … draw() intersect() * Character
Polygon Word Row draw() intersect() draw() intersect() draw() intersect() draw() intersect() 1 What’s missing from this picture? Spring 18 CSCI 2600, K. Kuzmin, A Milanova

14 Formatting Formatting displays the document
Many different formatting strategies are possible We would use different formatting strategies over the same hierarchical structure Each formatting strategy is complex Spring 18 CSCI 2600, K. Kuzmin, A Milanova

15 The Strategy Pattern Encapsulates an algorithm in an object Glyph *
draw() … FormattingStrategy compose() setDocument() Document 1 draw() insert(…) Strategy1 Strategy2 Strategy3 compose() compose() compose() Spring 18 CSCI 2600, K. Kuzmin, A Milanova

16 Embellishing the UI We would like to embellish the document display. One embellishment adds a border around the document area, another one adds a horizontal scroll bar and a third one adds a vertical scroll bar We would like to do this dynamically --- one can create any combination of embellished documents What pattern? Spring 18 CSCI 2600, K. Kuzmin, A Milanova

17 The Decorator Pattern Adds functionality, preserves interface 1 Glyph
* draw() intersect() component.draw(); Document DecoratedGlyph 1 draw() intersect() insert() 1 draw() component BorderDecorator ScrollDecorator draw() drawBorder() draw() drawScroll() Spring 18 CSCI 2600, K. Kuzmin, A Milanova

18 User Commands Editor supports many user “commands”: open and close, cut and paste, etc. There is different user interface for the same command E.g., close document through a pull-down menu item, close button, key shortcut, other Supports undo and redo! Spring 18 CSCI 2600, K. Kuzmin, A Milanova

19 A Naïve Design What’s wrong with this design? UIWidget draw() …
Document MenuItem ShortcutButton draw() intersect() insert() draw() … draw() … CloseItem CloseButton Spring 18 CSCI 2600, K. Kuzmin, A Milanova

20 The Command Pattern Separates MenuItems from Commands that do the work
onClick() … command execute() 1 1 Document command.execute(); Save Close open() save() close() execute() … execute() … … = new MenuItem(“Save”, new Save(document)); … = new MenuItem(“Close”, new Close(document)); … = new ShortcutButton(“Save”, new Save(document)); Spring 18 CSCI 2600, K. Kuzmin, A Milanova

21 Easy to Add Undo/Redo! Editor maintains a history (e.g., a stack) of commands that have been executed MenuItem Command command onClick() … execute() unexecute() 1 1 command.execute(); Cut Paste Document execute() unexecute() storedState execute() unexecute() storedState open() save() close() Spring 18 CSCI 2600, K. Kuzmin, A Milanova

22 Adding Spell Checking Requires traversal of document hierarchy
We want to avoid writing this functionality into the document structure We would like to add other traversals in the future, e.g., search, word count, hyphenation What pattern?

23 The Visitor Pattern Glyph * * draw() intersect() accept(Visitor)
Document Polygon Word draw() intersect() insert() accept(Visitor) draw() intersect() accept(Visitor) draw() intersect() accept(Visitor) 1 1 Spring 18 CSCI 2600, K. Kuzmin, A Milanova

24 Outline of Today’s Class
Behavioral patterns for traversing composites Visitor, conclusion! Behavioral pattern for traversal of containers Iterator Design exercise More patterns: Strategy and Command, others Odds and ends on creating objects Static factory methods, and clone

25 Static Factory Methods
Not the same as GoF Factory Method/Object Use static factory methods (typically) instead of, (sometimes) in addition to constructors class Boolean { private Boolean(boolean b) { … } public static Boolean valueOf(boolean b) { if (b) then return TRUE; else return FALSE; } The examples I used so far conform with the GoF definition of Factory method: we have the parallel hierarchy of Objects and their Products and each Object class creates its own product. The term “factory method” is used outside of this context. In general “Factory method” refers to any method that can return a Product (maybe a subtype), depending on the context.

26 Static Factory Methods in JDK
DateFormat class encapsulates knowledge on how to format a Date Options: Just date? Just time? date+time? where in the world? DateFormat df1 = DateFormat.getDateInstance(); DateFormat df2 = DateFormat.getTimeInstance(); Date today = new Date(); df1.format(today); // “Jul 4, 1776” df2.format(today); // “10:15:00 AM” Spring 18 CSCI 2600, K. Kuzmin, A Milanova

27 Advantages Does not need create a new object each time. Interning (use ==, save memory) Can have descriptive names Can hide classes java.util.EnumSet can be instantiated only by static factory methods: e.g., of(E e1, E e2) If less than 64 elements, creates a RegularEnumSet, otherwise creates a JumboEnumSet Spring 18 CSCI 2600, K. Kuzmin, A Milanova

28 Disadvantages Classes with public constructors cannot be subclassed
Look like regular static methods newInstance, getInstance of valueOf Spring 18 CSCI 2600, K. Kuzmin, A Milanova

29 Override clone() Judiciously
Remember Prototype creational pattern class Race { Bicycle bproto; // constructor Race(Bicycle bproto) { this.bproto = bproto; } Race createRace() { Bicycle bike1 = bproto.clone(); Spring 18 CSCI 2600, K. Kuzmin, A Milanova

30 Override clone() Judiciously
Object has protected Object clone() Each class can define a clone method that returns a copy of the receiver object: class Bicycle { Bicycle clone() { return new Bicycle(); } } So what’s the problem with clone()? Spring 18 CSCI 2600, K. Kuzmin, A Milanova

31 Override clone() Judiciously
To advertise that an object implements clone(), use the Cloneable interface: class Bicycle implements Cloneable { } Invoking Object.clone() on an object that does not implement Cloneable throws exception Object.clone() on an object that does implement Cloneable alters behavior of Object.clone(). Does a shallow copy. 1.

32 Cloning Point class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } Point p1 = new Point(2,10); try { Point p2 = p1.clone(); } catch (CloneNotSupportedException e) { ... } What happens? Compiles. At run-time throws CloneNotSupportedException. Spring 18 CSCI 2600, K. Kuzmin, A Milanova

33 Cloning Point again class Point implements Cloneable { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } Point p1 = new Point(2,10); try { Point p2 = p1.clone(); } catch (CloneNotSupportedException e) { ... } What happens? Compiles, and runs fine. Creates a new Point object with copies of 2 and 10 fields. Since these are simple types, it’s all good. Spring 18 CSCI 2600, K. Kuzmin, A Milanova

34 Cloning Point again class Point implements Cloneable { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public Point clone() { try { return (Point) super.clone(); } catch (CloneNotSupportedException e) {…} What happens here? Compiles and runs just fine. Can clone points, and it is ok since these are just ints. Using super.clone is the preferred way of cloning objects rather than calling a constructor. This is akin to constructors which initiate a chain of calls. Spring 18 CSCI 2600, K. Kuzmin, A Milanova

35 Cloning Stack TOTAL DISASTER! class Stack { private Object[] elements;
int size; public Stack clone() { try { return (Stack) super.clone(); } catch (CloneNotSupportedException e) {…} } TOTAL DISASTER! 1. Spring 18 CSCI 2600, K. Kuzmin, A Milanova

36 Cloning Stack better public Stack clone() { try { Stack result = (Stack) super.clone(); result.elements = elements.clone(); return result; } catch (CloneNotSupportedException e) { throw new AssertionError(); } Yet, not always possible to clone fields recursively 1. Spring 18 CSCI 2600, K. Kuzmin, A Milanova

37 Using clone(), recap A class that implement Cloneable should override clone(). It should first call super.clone(), then replace all fields appropriately Too complex! Better not to use Alternative: A copy constructor, or a static factory method analogous to a copy constructor 1.


Download ppt "Design Patterns, conclusion"

Similar presentations


Ads by Google