Design Patterns

# Design Patterns

## Design Patterns

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Design Patterns

2. Patterns • 1, 2, 3, … is a sequence that exhibits the pattern: The integers in their natural order

3. Another Sequence • 1, 3, 5, … • The pattern: The odd integers, in order

4. What is a Pattern? • A template or model for imitation • A dress pattern • A cookie cutter • As we shall see, an object-oriented design diagram • A set of rules • For the Fibonacci sequence, the rule is: the ith element (except for f0 and f1) is equal to the sum of the (i-1)st element and the (i-2)nd element.

5. Why are Patterns Useful? • Patterns describing infinite sequences eliminate having to enumerate all values 0, 1, 1, 2, 3, 5, 8, … Don’t have to list all the elements

6. Why are Patterns Useful? • A pattern can be a convenient membership test for a set of elements • Regular expressions denote patterns of strings • For example [a-zA-Z][a-zA-z0-9]* is a pattern representing identifiers • Compilers use regular expressions to test for identifiers

7. Why are Patterns Useful? • Knowledge of a pattern can enable one to easily produce new objects:

8. Why are Patterns Useful? • In particular, patterns discerned from existing situations may be applied to new situations a, b, c, … Monday, Tuesday, Wednesday, …

9. But Sometimes the Similarities are not Obvious

10. Patterns and Abstraction Which Bring Us To… • Do 1, 2, 3, … and Monday, Tuesday, Wednesday, … exhibit the same pattern?

11. Patterns and Abstraction 1, 2, 3, … the integers in their natural order Monday, Tuesday, Wednesday, … the days of the week in their natural order Are these the same pattern?

12. Patterns and Abstraction The pattern we really mean is The elements of some sequence taken in their natural order What about the fact that the integers are infinite and the days of the week are finite?

13. Some Patterns are Simple… ABC Jackson 5 Michael: you went to school to learn, girlThings you never, never knew before...… …Jermaine: sit yourself down, take a seatAll you gotta do is repeat after me.J5: a b cMichael: easy as...J5: 1 2 3Michael: or simple as...J5: do re miMichael: abc, 123, baby, you and me girl!

14. Others are Less Obvious… • 2, 3, 5, 7, … • primes • March, April, June, … • Months without a ‘Y’ in their names in natural order Mensa likes to use patterns like these as part of their qualification test

15. Some are Quite Difficult… • 6, 28, 496, … • perfect numbers • e, t, a, … • most frequent letters in the English language in descending order

16. … And Some are Just Downright Ornery Especially if they’re not mathematical and you don’t know the context • 214, 232, 234, … • Classrooms on 2nd floor of New Ingersoll from east to west • 1110, 2210, 3110, … • For cryin’ out loud– you’re CIS majors!

17. And Now For Something Completely Different…Summing Integers Read from a File cin >> i; while (i >= 0) { total += i; cin >> i; }

18. Finding the Maximum Double in a File cin >> d; while (cin) { if (d > max) max = d; cin >> d; }

19. Building a String from a Line of Characters i = 0; c = getchar(); while (c != ‘\n’ && c != EOF) s[i++] = c; c = getchar(); } s[i] = ‘\0’;

20. Three Individual Pieces of Code… • Different datum types • int, double, char • Different end-of-input conditions • negative datum, end-of-file, end-of-line/end-of-file • Different tasks: • summing, maximum, string construction

21. … and Yet A Pattern Emerges • In all three cases: • Values are read from a file • A condition is used to test for end-of-input • The values are processed in some fashion • A ‘priming-the-pump’ technique is used

22. An Input Loop Pattern read first item while (still more items) { process item read next item }

23. Why Are Such Patterns Useful? • Avoids ‘reinventing the wheel’ • Avoids making the same mistakes over and over again • Speeds up the development process • ‘Reusability’ of sorts

24. Design Patterns • Pattern concept applied to software design • Not a finished product • Reuseability of design ‘ideas’ • Many patterns crop up over and over again

25. A Non-Software Example- Flywheel • A flywheel is a massive rotating disk • The basic idea is to accelerate the flywheel to a very high speed and thus maintain the energy as rotational energy using the disk.

26. Flywheel - Samples

27. Why a Flywheel? • In the 70’s engineers were looking for a low-emissions, non-internal-combustion vehicle. • Wanted to be able to ‘charge’ the vehicle and have it store that charge • Charging involved bringing the flywheel up to a high speed • Batteries were too bulky, heavy • Would need tens of batteries for a small vehicle

28. Flywheel – Useful For • Storing kinetic energy – often in a fairly small space • Maintaining a uniform force. • Production of high power pulses • Can also be used to create a form of gyroscopic effect

29. Flywheel – Advantages • Not affected by temperature changes • No limit to energy stored • Simple to measure stored force (measure rotation speed)

30. Flywheel – Disadvantages • Danger of explosive shattering of wheel

31. Flywheel – Parts • Massive wheel • Axle • Bearings

32. Flywheel - Applications • Low-cost toys (the kind you wind up by running the wheels along the floor) • Energy-efficient cars (during braking, surplus energy is used to accelerate the flywheel which can subsequently power the driveshaft) • Used on satellites to point the instruments in correct direction • Potters wheel

33. Flywheel - Summary • Note the variety of applications • Yet all use the same basic design pattern

34. Flywheel - Summary • Notice what we did here • Provided a motivational situation (low-emission vehicle) • Presented the purpose of the flywheel • Described when to use one • Presented the parts of the flywheel • Discussed advantages and disadvantages • Gave known applications • Presented some samples

35. A Simple Software Example • You’ve got a program from CISC 3130 (Data Structures) • Written in C++ • Uses a stack class template • Which you wrote (whole point of assignment) • Massive application • Hundreds of modules • Thousands of lines of code • Ok, Ok, two hundred lines of code in one file • Stack usage scattered throughout system

36. Our Simple Software Example • After CISC 3130, you learn about the STL (Standard Template Library) • Library of useful data structures, including those you learned in 3130 • You decide you want to play with it • Good to know for a tech interview • So you toss out your stack and begin using the one from the STL

37. The Problem • Your stack’s operations: • push – places argument on top of stack • pop – pops stack returning value • isEmpty – true if empty • STL’s stack’s operations: • push – same • peek – returns top of stack • pop – pops stack, no value returned • empty – different name, same semantics There’s a mismatch in the interfaces

38. Solution #1 • Change the application code to conform to the new operations

39. The Changes • Replace s.isEmpty();// yours with s.empty(); // STL’s and s.pop();// yours with s.peek(); // STL’s s.pop(); Global edit replace?

40. ??? !!! void clear() { while(!s.isEmpty()) s.pop(); } void clear() { while(!s.empty()) s.peek(); s.pop(); } #^%\$!!! Scratch that solution!!

41. So?? • What’s Plan B?

42. Plan B • Add a new class, StackAdapter • StackAdapter declares a member variable of type stack (from the STL). • StackAdapter defines functions corresponding to the ones in your original stack class • Some of the functions do nothing more than call corresponding functions of the STL stack • Other functions act as adapters between the old and new semantics

43. The StackAdapter Class template <class E> class StackAdapter { public: push(E val) {s.push(val);} E pop() { E x = s.peek(); s.pop(); return x; } bool isEmpty() {return s.empty();} private: stack<E> s; }

44. The Adapter Pattern • Plan B employs a design pattern known as Adapter • The Adapter pattern Converts the interface of a class into another interface clients expect. Adapter lets classes work together that otherwise couldn’t because of incompatible interfaces

45. The Adapter Pattern Visually StackAdapter push() pop() isEmpty() x = s. pop() s.pop(); return x; s.isEmpty() s Stack push() pop() empty()

46. You May Have Seen Something Similar • For example, when coding binary search… • The recursive call for binary search is bool binsrch(int a[], int lo, int hi) … but the user wants to make the call bool binsearch(int a[], int n) • We resolve this by adding an intermediate function: bool binsearch(int a[], int n) { return binsrch(a, 0, n-1); } This is the a procedural analogy of the Adapter pattern; binsearch is usually called a wrapper function.

47. Design Patterns • Introduced by architect Christopher Alexander (A Pattern Language: Towns, Buildings, Construction) in the context of buildings and towns: “Each pattern describes a problem which occurs over and over again in our environment, the describes the core of the solution to that problem, in such a way that you can use the solution a million times over, without ever doing it the same way twice.”

48. Architectural Design Patterns • “A PLACE TO WAIT” • Bus stop • Waiting room • adresses the common aspects of their design • “ARCADES” - “covered walkways at edges of buildings, partly inside, partly outside” http://architypes.net/patterns.php

49. ‘The Gang of Four’ Book • Introduced design patterns to software design • Much of this talk based upon this text • In fact, it’s fair to say that one purpose of this talk is to provide a guide to how to read this text • Bulk of text is a catalog of patterns