Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Design Patterns 1CS 221 - Computer Science II.

Similar presentations


Presentation on theme: "Introduction to Design Patterns 1CS 221 - Computer Science II."— Presentation transcript:

1 Introduction to Design Patterns 1CS 221 - Computer Science II

2 2 Overview Design Patterns in Software Why? What are design patterns? What they’re good for How we develop / classify them The Iterator Pattern CS 221 - Computer Science II

3 3 Recurring Design Structures OO systems exhibit recurring structures that promote abstraction flexibility modularity elegance Therein lies valuable design knowledge Problem: Capturing, communicating, and applying this knowledge CS 221 - Computer Science II

4 4 Design Patterns "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice." Christopher Alexander, A Pattern Language: Towns/Buildings/Construction, 1977 A object-oriented design pattern systematically names, explains and evaluates an important and recurring design in object-oriented systems

5 Patterns in engineering How do other engineers find and use patterns? Mature engineering disciplines have handbooks describing successful solutions to known problems Automobile designers don't design cars from scratch  Reuse standard designs with successful track records Should software engineers make use of patterns? Why?  Developing software from scratch is expensive  Patterns support reuse of software architecture and design

6 CS 221 - Computer Science II6 Design Patterns The landmark book on software design patterns is: Design Patterns: Elements of Reusable Object-Oriented Software Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Addison-Wesley, 1995 This is also known as the GOF (“Gang- of-Four”) book.

7 7 A Design Pattern… abstracts a recurring design structure comprises class and/or object  dependencies  structures  interactions  conventions names / specifies the design structure explicitly distills design experience CS 221 - Computer Science II

8 8 Goals Codify good design distill / generalize experience aid to novices / experts alike Give design structures explicit names common vocabulary reduced complexity greater expressiveness Capture and preserve design information articulate design decisions succinctly improve documentation Facilitate restructuring / refactoring patterns are interrelated additional flexibility CS 221 - Computer Science II

9 9 Design Pattern Template (1st half) N AME scope purpose Intent short description of the pattern & its purpose Also Known As Any aliases this pattern is known by Motivation motivating scenario demonstrating pattern’s use Applicability circumstances in which pattern applies Structure graphical representation of the pattern using modified UML notation Participants participating classes and/or objects & their responsibilities CS 221 - Computer Science II

10 10 Design Pattern Template (2nd half)... Collaborations how participants cooperate to carry out their responsibilities Consequences the results of application, benefits, liabilities Implementation pitfalls, hints, techniques, plus language-dependent issues Sample Code sample implementations in C++, Java, C#, Smalltalk, C, etc. Known Uses examples drawn from existing systems Related Patterns discussion of other patterns that relate to this one CS 221 - Computer Science II

11 11 O BSERVER object behavioral Intent define a one-to-many dependency between objects so that when one object changes state, all dependents are notified & updated Applicability an abstraction has two aspects, one dependent on the other a change to one object requires changing untold others an object should notify unknown other objects Structure

12 12 O BSERVER (cont’d) object behavioral Consequences +modularity: subject & observers may vary independently +extensibility: can define & add any number of observers +customizability: different observers offer different views of subject –unexpected updates: observers don’t know about each other –update overhead: might need hints or filtering Implementation subject-observer mapping dangling references update protocols: the push & pull models registering modifications of interest explicitly Known Uses Smalltalk Model-View-Controller (MVC) InterViews (Subjects & Views, Observer/Observable) Andrew (Data Objects & Views) Pub/sub middleware (e.g., CORBA Notification Service, Java Messaging Service) Mailing lists

13 Design Patterns are NOT Data structures that can be encoded in classes and reused as is (i.e., linked lists, hash tables) Complex domain-specific designs (for an entire application or subsystem) If they are not familiar data structures or complex domain-specific subsystems, what are they? They are: “Descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.”

14 Three Types of Patterns Creational patterns: Deal with initializing and configuring classes and objects Structural patterns: Deal with decoupling interface and implementation of classes and objects Composition of classes or objects Behavioral patterns: Deal with dynamic interactions among societies of classes and objects How they distribute responsibility

15 Creational Patterns Abstract Factory: Factory for building related objects Builder: Factory for building complex objects incrementally Factory Method: Method in a derived class creates associates Prototype: Factory for cloning new instances from a prototype Singleton: Factory for a singular (sole) instance

16 Structural Patterns Describe ways to assemble objects to realize new functionality Added flexibility inherent in object composition due to ability to change composition at run-time not possible with static class composition Example: ProxyProxy Proxy: acts as convenient surrogate or placeholder for another object.  Remote Proxy: local representative for object in a different address space  Virtual Proxy: represent large object that should be loaded on demand  Protected Proxy: protect access to the original object

17 Structural Patterns Adapter: Translator adapts a server interface for a client Bridge: Abstraction for binding one of many implementations Composite: Structure for building recursive aggregations Decorator: Decorator extends an object transparently Facade: Simplifies the interface for a subsystem Flyweight: Many fine-grained objects shared efficiently. Proxy: One object approximates another

18 Behavioral Patterns Chain of Responsibility: Request delegated to the responsible service provider Command: Request or Action is first-class object, hence re-storable Iterator: Aggregate and access elements sequentially Interpreter: Language interpreter for a small grammar Mediator: Coordinates interactions between its associates Memento: Snapshot captures and restores object states privately

19 Behavioral Patterns (cont.) Observer: Dependents update automatically when subject changes State: Object whose behavior depends on its state Strategy: Abstraction for selecting one of many algorithms Template Method: Algorithm with some steps supplied by a derived class Visitor: Operations applied to elements of a heterogeneous object structure

20 Patterns in software libraries AWT and Swing use Observer pattern Iterator pattern in C++ template library & JDK Façade pattern used in many student- oriented libraries to simplify more complicated libraries! Bridge and other patterns recurs in middleware for distributed computing frameworks …

21 Benefits of Design Patterns Design patterns enable large-scale reuse of software architectures and also help document systems Patterns explicitly capture expert knowledge and design tradeoffs and make it more widely available Patterns help improve developer communication Pattern names form a common vocabulary

22 22 Liabilities of Patterns Require significant tedious and error-prone human effort to handcraft pattern implementations design reuse Can be deceptively simple uniform design vocabulary May limit design options Leaves some important details unresolved CS 221 - Computer Science II

23 Iterator Design Pattern CS 221 - Computer Science II23

24 24 Spelling Checking & Hyphenation Goals: analyze text for spelling errors introduce potential hyphenation sites Constraints/forces: support multiple algorithms don’t tightly couple algorithms with document structure

25 25 Solution: Encapsulate Traversal Iterator encapsulates a traversal algorithm without exposing representation details to callers uses Glyph’s child enumeration operation This is an example of a “preorder iterator” CS 221 - Computer Science II

26 26 I TERATOR object behavioral Intent access elements of a container without exposing its representation Applicability require multiple traversal algorithms over a container require a uniform traversal interface over different containers when container classes & traversal algorithm must vary independently Structure CS 221 - Computer Science II

27 27 I TERATOR (cont’d) object behavioral int main (int argc, char *argv[]) { vector args; for (int i = 0; i < argc; i++) args.push_back (string (argv[i])); for (vector ::iterator i (args.begin ()); i != args.end (); i++) cout << *i; cout << endl; return 0; } Iterators are used heavily in the C++ Standard Template Library (STL) The same iterator pattern can be applied to any STL container! for (Glyph::iterator i = glyphs.begin (); i != glyphs.end (); i++)... CS 221 - Computer Science II

28 28 I TERATOR (cont’d) object behavioral Consequences +flexibility: aggregate & traversal are independent +multiple iterators & multiple traversal algorithms –additional communication overhead between iterator and aggregate Implementation internal versus external iterators violating the object structure’s encapsulation robust iterators synchronization overhead in multi-threaded programs batching in distributed & concurrent programs Known Uses C++ STL iterators JDK Enumeration, Iterator Unidraw Iterator CS 221 - Computer Science II

29 29 Iterating Through A Vector Suppose we want to “step through” a Vector object, retrieving each of the objects stored in the vector one at a time:

30 CS 221 - Computer Science II30 Iterating Through A Vector import java.util.*; public class IterationExample { public static void main(String args[]) { Vector v = new Vector(); // Put some Complex number // objects in the vector. v.addElement(new Complex(3.2, 1.7)); v.addElement(new Complex(7.6)); v.addElement(new Complex()); v.addElement(new Complex(-4.9, 8.3)); Complex c; for (int i = 0; i < v.size(); i++) { c = (Complex)v.elementAt(i); System.out.println(c); }

31 CS 221 - Computer Science II31 Iterating Through A Vector This approach works well for vectors because the elements of a vector can be retrieved by specifying their position: v.elementAt(i); We start by retrieving element 0, then retrieve element 1, etc., until we retrieve the last element (at position v.size()- 1)

32 CS 221 - Computer Science II32 What About Other Collection Classes? This approach doesn't work well for all collection classes: what would a position (i.e. index) mean for a Set ? values stored in a Hashtable object are retrieved by keys, not by position Is it possible to come up with a more general approach, that can be used to iterate over any collection of objects? There must be a general design solution to this…

33 CS 221 - Computer Science II33 Collection Classes & Iterators The Collection interface provides an iterator() method to be implemented by all concrete collections: Iterator iterator() Collection plays the role of the “Aggregate” in the GoF Iterator pattern A “ConcreteAggregate” (i.e. Vector, LinkedList …) implementing this method should create and return a iterator object

34 CS 221 - Computer Science II34 Iterator Objects An Iterator object provides two main methods: public boolean hasNext()  returns true if the Iterator object has more elements (objects) that have not yet been returned by next() public Object next()  returns the next element (object) from the iteration

35 CS 221 - Computer Science II35 Iterating Through a Vector // Create a vector object and initialize // it with Complex objects Complex c; Iterator i; i = v.iterator(); while (i.hasNext()) { c = (Complex)i.next(); System.out.println(c); }

36 CS 221 - Computer Science II36 Iterating Any Collection For instance, the code below shows how AbstractCollection implements addAll() without making any assumption on the nature of the collection that is passed as an argument: public boolean addAll(Collection from) { Iterator iter = from.iterator(); boolean modified = false; while (iter.hasNext()) if (add(iter.next())) modified = true; return modified; }

37 CS 221 - Computer Science II37 Building an Iterator Suppose we have a class called CircularList that provides these methods (other CircularList methods not shown here): // Constructor. public CircularList(); // Return the count of the number of // elements in the list. public int count(); // Return the element stored at the specified // position in the CircularList. public Object get(int index); // Remove the element stored at the specified // position in the CircularList. public Object remove(int index);

38 CS 221 - Computer Science II38 Building an Iterator How do we build an iterator (i.e., an Iterator object) for this class? We want an object that lets us do this: CircularList l = new CircularList();... //store integers in the list... Iterator i = l.iterator(); while (i.hasNext()) { System.out.println(i.next()); }

39 CS 221 - Computer Science II39 The Iterator Interface When we look through the documentation for the Java API, we discover that Iterator is an interface, not a class: public interface Iterator { public boolean hasNext(); public Object next(); public void remove(); } An Iterator object is an instance of a class that implements the Iterator interface; i.e., defines the hasNext(), next(), and remove() methods


Download ppt "Introduction to Design Patterns 1CS 221 - Computer Science II."

Similar presentations


Ads by Google