introduction to design patterns 1cs 221 - computer science ii

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

Upload: preston-charles

Post on 31-Dec-2015

223 views

Category:

Documents


3 download

TRANSCRIPT

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

Introduction to Design Patterns

1CS 221 - Computer Science II

Page 2: Introduction to Design Patterns 1CS 221 - Computer Science II

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

Page 3: Introduction to Design Patterns 1CS 221 - Computer Science II

3

Recurring Design StructuresOO 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

Page 4: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 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

Page 5: Introduction to Design Patterns 1CS 221 - Computer Science II

Patterns in engineeringHow 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

Page 6: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 6

Design PatternsThe 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.

Page 7: Introduction to Design Patterns 1CS 221 - Computer Science II

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

Page 8: Introduction to Design Patterns 1CS 221 - Computer Science II

8

GoalsCodify 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

Page 9: Introduction to Design Patterns 1CS 221 - Computer Science II

9

Design Pattern Template (1st half)NAME scope purpose

Intentshort description of the pattern & its purpose

Also Known AsAny aliases this pattern is known by

Motivationmotivating scenario demonstrating pattern’s use

Applicabilitycircumstances in which pattern applies

Structuregraphical representation of the pattern using modified UML

notation

Participantsparticipating classes and/or objects & their responsibilities

CS 221 - Computer Science II

Page 10: Introduction to Design Patterns 1CS 221 - Computer Science II

10

Design Pattern Template (2nd half)

...

Collaborationshow participants cooperate to carry out their responsibilities

Consequencesthe results of application, benefits, liabilities

Implementationpitfalls, hints, techniques, plus language-dependent issues

Sample Codesample implementations in C++, Java, C#, Smalltalk, C, etc.

Known Usesexamples drawn from existing systems

Related Patternsdiscussion of other patterns that relate to this one

CS 221 - Computer Science II

Page 11: Introduction to Design Patterns 1CS 221 - Computer Science II

11

OBSERVER object behavioral

Intentdefine 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

Page 12: Introduction to Design Patterns 1CS 221 - Computer Science II

12

OBSERVER (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

Page 13: Introduction to Design Patterns 1CS 221 - Computer Science II

Design Patterns are NOTData 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.”

Page 14: Introduction to Design Patterns 1CS 221 - Computer Science II

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

Page 15: Introduction to Design Patterns 1CS 221 - Computer Science II

Creational PatternsAbstract Factory:

Factory for building related objectsBuilder:

Factory for building complex objects incrementallyFactory Method:

Method in a derived class creates associatesPrototype:

Factory for cloning new instances from a prototypeSingleton:

Factory for a singular (sole) instance

Page 16: Introduction to Design Patterns 1CS 221 - Computer Science II

Structural PatternsDescribe 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: Proxy 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

Page 17: Introduction to Design Patterns 1CS 221 - Computer Science II

Structural PatternsAdapter:

Translator adapts a server interface for a clientBridge:

Abstraction for binding one of many implementationsComposite:

Structure for building recursive aggregationsDecorator:

Decorator extends an object transparentlyFacade:

Simplifies the interface for a subsystemFlyweight:

Many fine-grained objects shared efficiently.Proxy:

One object approximates another

Page 18: Introduction to Design Patterns 1CS 221 - Computer Science II

Behavioral PatternsChain of Responsibility:

Request delegated to the responsible service providerCommand:

Request or Action is first-class object, hence re-storableIterator:

Aggregate and access elements sequentiallyInterpreter:

Language interpreter for a small grammarMediator:

Coordinates interactions between its associatesMemento:

Snapshot captures and restores object states privately

Page 19: Introduction to Design Patterns 1CS 221 - Computer Science II

Behavioral Patterns (cont.)

Observer: Dependents update automatically when subject

changesState:

Object whose behavior depends on its stateStrategy:

Abstraction for selecting one of many algorithmsTemplate Method:

Algorithm with some steps supplied by a derived class

Visitor: Operations applied to elements of a heterogeneous

object structure

Page 20: Introduction to Design Patterns 1CS 221 - Computer Science II

Patterns in software libraries

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

Page 21: Introduction to Design Patterns 1CS 221 - Computer Science II

Benefits of Design Patterns

Design patterns enable large-scale reuse of software architectures and also help document systemsPatterns explicitly capture expert knowledge and design tradeoffs and make it more widely availablePatterns help improve developer communicationPattern names form a common vocabulary

Page 22: Introduction to Design Patterns 1CS 221 - Computer Science II

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

Page 23: Introduction to Design Patterns 1CS 221 - Computer Science II

Iterator Design Pattern

CS 221 - Computer Science II 23

Page 24: Introduction to Design Patterns 1CS 221 - Computer Science II

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

Page 25: Introduction to Design Patterns 1CS 221 - Computer Science II

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

Page 26: Introduction to Design Patterns 1CS 221 - Computer Science II

26

ITERATOR object behavioralIntent

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

Page 27: Introduction to Design Patterns 1CS 221 - Computer Science II

27

ITERATOR (cont’d) object behavioral

int main (int argc, char *argv[]) { vector<string> args; for (int i = 0; i < argc; i++)

args.push_back (string (argv[i])); for (vector<string>::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

Page 28: Introduction to Design Patterns 1CS 221 - Computer Science II

28

ITERATOR (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

Page 29: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 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:

Page 30: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 30

Iterating Through A Vectorimport 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); } }}

Page 31: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 31

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)

Page 32: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 32

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…

Page 33: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 33

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

Page 34: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 34

Iterator ObjectsAn 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

Page 35: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 35

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);

}

Page 36: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 36

Iterating Any CollectionFor 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; }

Page 37: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 37

Building an IteratorSuppose 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);

Page 38: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 38

Building an IteratorHow 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());}

Page 39: Introduction to Design Patterns 1CS 221 - Computer Science II

CS 221 - Computer Science II 39

The Iterator InterfaceWhen 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