Design Patterns - PowerPoint PPT Presentation

design patterns n.
Skip this Video
Loading SlideShow in 5 Seconds..
Design Patterns PowerPoint Presentation
Download Presentation
Design Patterns

play fullscreen
1 / 125
Design Patterns
Download Presentation
Download Presentation

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, 3120, 3130, 3140, … • For cryin’ out loud– you’re CIS majors!

  17. Patterns Within Patterns A B C

  18. And Now For Something Completely Different…Summing Integers Read from a File scanf(“%d”, &i); while (i >= 0) { total += i; scanf(“%d”, &i); }

  19. Finding the Maximum Double in a File result = scanf(“%f”, &d); while (result != EOF) { if (d > max) max = d; scanf(“%f”, &d); }

  20. 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’;

  21. 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

  22. … 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

  23. An Input Loop Pattern read first item while (not end-of-input) { process item read next item }

  24. 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

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

  26. 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.

  27. Flywheel - Samples

  28. 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

  29. 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

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

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

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

  33. 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

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

  35. 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

  36. A Simple Software Example • You’ve got a program from CIS 3130 • 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

  37. But First-A Word From Our Sponsors A stack class template is a definition of a stack class in which the element type of the stack is supplied when a particular stack is declared: stack<int> si; stack<ActivationRecord> sa;

  38. Back To Our Simple Software Example • In 3130, you may have learned 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

  39. 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 – same semantics

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

  41. 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?

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

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

  44. 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

  45. 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; }

  46. 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

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

  48. 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.

  49. 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.”

  50. 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”