1 / 132

Design Patterns

Design Patterns. Patterns. 1, 2, 3, … is a sequence that exhibits the pattern: The integers in their natural order. Another Sequence. 1, 3, 5, … The pattern: The odd integers, in order. What is a Pattern?. A template or model for imitation A dress pattern A cookie cutter

buck
Télécharger la présentation

Design Patterns

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

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 OO 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 “Beat your plowshares into swords …”

  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 • 1.5, 4.1, 11, … • For cryin’ out loud– you’re CIS majors!

  17. Patterns Within Patterns… A B C

  18. … and Patterns of Patterns 1, 2, 3, … 1, 3, 5, … 1, 4, 7, … ??, ?? ??, …

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

  20. Finding the Questions in a File (Java) line = br.readLine(); while (line != null) { if (line.indexOf("?") >= 0) questions.add(line); line = br.readLine(); }

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

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

  23. … 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 • Probably the first pattern you learn in CS 1

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

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

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

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

  28. Flywheel - Samples

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

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

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

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

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

  34. 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) • Potters wheel • Used on satellites to point the instruments in correct direction

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

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

  37. A Simple Software Example • You’ve got a program from CIS 22 • 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 • But still, stack usage is scattered throughout system

  38. But First-A Word From Our Sponsors For those of you who may not know: a class, is essentially a structure that contain contain functions as well as fields. a template is a parameterized piece of code whose arguments are supplied by the application programmer Thus, 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 of ints stack<ActivationRecord> sa; // stack of ActivationRecords

  39. Back To Our Simple Software Example • After CIS 22, you learn about the STL (Standard Template Library) • Library of useful data structures, including those you learned in 22 • 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

  40. 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 • top – returns top of stack • pop – pops stack, no value returned • empty – same semantics E pop() { E elem = arr[top]; top--; return e; } void pop() {top--;} E top() {return arr[top];}

  41. Solution #1 • Change the application code to conform to the new operations • Change all occurrences of isEmpty to empty • Replace pop (which used to return the element) with a top followed by a pop: s.pop(); s.top(); s.pop();

  42. ??? !!! void clear() { while(!s.isEmpty()) s.pop(); } void clear() { while(!s.empty()) s.top(); 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 type • Other functions act as adapters between the old and new semantics • In particular, StackAdapter’s pop function will carry out the necessary (STL) top and pop operations on the STL stack

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

  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. peek() 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, int val) i.e, upper and lower bound parameters are required … … but the user of the search wants to make the call bool binsearch(int a[], int n, int val) that is, simply the number of elements (that’s the standard signature for an array search in C/C++)

  49. Using A Wrapper Function • The classical resolution to this problem is to add an intermediary function: bool binsearch(int a[], int n) { return binsrch(a, 0, n-1); } This is the the procedural analogy of the Adapter pattern; binsearch is usually called a wrapper function. This pattern is often taught in 15 or 22.

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

More Related