Design Patterns: A Lightweight Introduction

1,726 views

Published on

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,726
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
18
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Design Patterns: A Lightweight Introduction

  1. 1. DESIGN PATTERNS hugo sereno ferreira . joão pascoal faria . jorge barbosa . nuno floresA L IG H TW E I G H T INTROD UC TION
  2. 2. ARCHITECTURE ... a cabana seems simple ...
  3. 3. ARCHITECTURE ... easier than an house ...
  4. 4. ARCHITECTURE... child’s play next to a building ...
  5. 5. ARCHITECTURE... but nothing compared to a city!
  6. 6. WHERE’S THE DIFFERENCES?• Size. From a small cabana, to a large city.• Cost. From less than €1k, to more than €1.000.000k• Time. Taking a day, to evolving through centuries.• Process. Doing as an hobby v.s. planning.• Skills. From a layman, to highly qualified professionals.• Risk. Vacations v.s. a population of millions.• ...
  7. 7. FINDING THE BEST DESIGN time – – + scope – cost – + quality
  8. 8. DEFINITION“ Architecture is the process and product of planning, designing and constructing physical form, space and ambience that reflect functional, technical, social, and aesthetic considerations. Wikipedia
  9. 9. SOFTWARE?“ ... the process and product of planning, designing and constructing logical form, space and ambience that reflect functional, technical, social, and aesthetic considerations.
  10. 10. QUALITY IN SOFTWARE✦ accessibility ✦ configurability ✦ integrity ✦ relevance ✦ survivability✦ accountability ✦ correctness ✦ interchangeability ✦ reliability ✦ sustainability✦ accuracy ✦ customizability ✦ interoperability ✦ repeatability ✦ tailorability✦ adaptability ✦ degradability ✦ learnability ✦ reproducibility ✦ testability✦ administrability ✦ demonstrability ✦ maintainability ✦ responsiveness ✦ timeliness✦ affordability ✦ dependability ✦ manageability ✦ reusability ✦ understandability✦ agility ✦ deployability ✦ mobility ✦ robustness ✦ usability✦ auditability ✦ distributability ✦ modularity ✦ safety ✦ ...✦ availability ✦ durability ✦ nomadicity ✦ scalability✦ credibility ✦ evolvability ✦ operability ✦ seamlessness✦ standards compliance ✦ extensibility ✦ portability ✦ serviceability✦ process capabilities ✦ fidelity ✦ precision ✦ securability✦ compatibility ✦ flexibility ✦ predictability ✦ simplicity✦ composability ✦ installability ✦ recoverability ✦ stability
  11. 11. OBJECTIVE ATTRIBUTES✦ accessibility ✦ configurability ✦ integrity ✦ relevance ✦ survivability✦ accountability ✦ correctness ✦ interchangeability ✦ reliability ✦ sustainability✦ accuracy ✦ customizability ✦ interoperability ✦ repeatability ✦ tailorability✦ adaptability ✦ degradability ✦ learnability ✦ reproducibility ✦ testability✦ administrability ✦ demonstrability ✦ maintainability ✦ responsiveness ✦ timeliness✦ affordability ✦ dependability ✦ manageability ✦ reusability ✦ understandability✦ agility ✦ deployability ✦ mobility ✦ robustness ✦ usability✦ auditability ✦ distributability ✦ modularity ✦ safety ✦ ...✦ availability ✦ durability ✦ nomadicity ✦ scalability✦ credibility ✦ evolvability ✦ operability ✦ seamlessness✦ standards compliance ✦ extensibility ✦ portability ✦ serviceability✦ process capabilities ✦ fidelity ✦ precision ✦ securability✦ compatibility ✦ flexibility ✦ predictability ✦ simplicity✦ composability ✦ installability ✦ recoverability ✦ stability
  12. 12. SUBJECTIVE ATTRIBUTES?✦ accessibility ✦ configurability ✦ integrity ✦ relevance ✦ survivability✦ accountability ✦ correctness ✦ interchangeability ✦ reliability ✦ sustainability✦ accuracy ✦ customizability ✦ interoperability ✦ repeatability ✦ tailorability✦ adaptability ✦ degradability ✦ learnability ✦ reproducibility ✦ testability✦ administrability ✦ demonstrability ✦ maintainability ✦ responsiveness ✦ timeliness✦ affordability ✦ dependability ✦ manageability ✦ reusability ✦ understandability✦ agility ✦ deployability ✦ mobility ✦ robustness ✦ usability✦ auditability ✦ distributability ✦ modularity ✦ safety ✦ ...✦ availability ✦ durability ✦ nomadicity ✦ scalability✦ credibility ✦ evolvability ✦ operability ✦ seamlessness✦ standards compliance ✦ extensibility ✦ portability ✦ serviceability✦ process capabilities ✦ fidelity ✦ precision ✦ securability✦ compatibility ✦ flexibility ✦ predictability ✦ simplicity✦ composability ✦ installability ✦ recoverability ✦ stability
  13. 13. WHAT DOES GOOD CODE LOOK LIKE?
  14. 14. OBFUSCATION? Cvoid qs(int l[], int m, int n) { int kk, i, j, k; if (m < n){ k = cp(m,n); s(&l[m], &l[k]); kk = l[m]; i = m + 1; j = n;while(i <= j) { while((i <= n) && (l[i] <= kk)) i++; while((j>= m) && (l[j] > kk)) j--; if (i < j) s(&l[i], &l[j]); } s(&l[m], &l[j]); qs(l, m, j-1); qs(l, j+1, n); }}
  15. 15. CODE? Cvoid qs(int l[], int m, int n) {! int kk, i, j, k;! if (m < n) {! ! k = cp(m,n);! ! s(&l[m], &l[k]);! ! kk = l[m];! ! i = m + 1; j = n;! ! while(i <= j) {! ! ! while((i <= n) && (l[i] <= kk)) i++;! ! ! while((j >= m) && (l[j] > kk)) j--;! ! ! if (i < j) s(&l[i], &l[j]);! ! }! !! ! s(&l[m], &l[j]);! !! ! qs(l, m, j-1);! ! qs(l, j+1, n);! }}
  16. 16. ART? Cvoid quicksort(int list[], int m, int n) {! int key, i, j, k;! if (m < n) {! ! k = choose_pivot(m,n);! ! swap(&list[m], &list[k]);! ! key = list[m];! ! i = m + 1; j = n;! ! while(i <= j) {! ! ! while((i <= n) && (list[i] <= key)) i++;! ! ! while((j >= m) && (list[j] > key)) j--;! ! ! if (i < j) swap(&list[i], &list[j]);! ! }! !! ! swap(&list[m], &list[j]);! !! ! quicksort(list, m, j-1);! ! quicksort(list, j+1, n);! }}
  17. 17. ABSORPTION? HASKELLqs [] = []qs (x:xs) = qs (filter (< x) xs) ++ [x] ++ qs (filter (>= x) xs)
  18. 18. CONDITIONALS... C# class Employee ... int payAmount() { Employee switch(type) {– monthlySalary case ENGINEER:– bonus return monthlySalary;– totalSales case SALESMAN:– type return monthlySalary + 0.1 * totalSales;+ payAmount case MANAGER: return monthlySalary + bonus; default: throw Exception("Incorrect Employee"); } }
  19. 19. ... V.S. POLYMORPHISM C# abstract class Employee ... Employee abstract int payAmount();– monthlySalary+ payAmount class Engineer: Employee ... int payAmount() { Engineer return monthlySalary; + payAmount } Manager class Salesman: Employee ... – bonus int payAmount() { + payAmount return monthlySalary + 0.1 * totalSales; } Salesman – totalSales class Manager: Employee ... + payAmount int payAmount() { return monthlySalary + bonus; }
  20. 20. IS GOOD CODEDIFFERENT IN FORM?
  21. 21. SOFTWARE DESIGNObject Oriented Design is more than just drawing diagrams:• Good OO designers rely on lots of experience• OO systems exhibit recurring structures that promote: abstraction flexibility modularity elegance• Therein lies valuable design knowledge• This reusable knowledge is captured through patterns
  22. 22. ALEXANDER’S PATTERN... a recognized good solution for a recurrent problem,which balances all relevant forces, optimizing the tradeoffsfor a specific purpose. P = ⟨ problem, forces, solution ⟩... are prescriptive rather than descriptive. It drives thedesigner to make a choice based on the forces and theresulting consequences.
  23. 23. PATTERNS ARE EVERYWHERE ... in nature ...
  24. 24. PATTERNS ARE EVERYWHERE ... in music ...
  25. 25. PATTERNS ARE EVERYWHERE ... in architecture ...
  26. 26. PATTERNS ARE EVERYWHERE ... in art ...
  27. 27. PATTERNS ARE EVERYWHERE ... in mathematics ...
  28. 28. WHY PATTERNS?“ Patterns analyze and formalize empirical knowledge in search for stronger invariants, allowing rational design choices and uncovering newer abstractions.
  29. 29. LIGHT ON TWO SIDES **Once the buildings major rooms are in position, we have to fix itsactual shape... “ When they have a choice, people will always gravitate to those rooms which have light on two sides, and leave the rooms which are lit only from one side unused and empty.
  30. 30. LIGHT ON TWO SIDES **Locate each room so that it has outdoor space outside it on atleast two sides, and then place windows in these outdoor wallsso that natural light falls into every room from more than onedirection.
  31. 31. DESIGN PATTERNS• Gamma et al. Design Patterns: Elements of Reusable Object-Oriented Software.• It presents 3 categories of 23 interconnected patterns on OO design.• It’s taught worldwide in CS/SE as an introductory book on software architecture and design: • Singleton, • Proxy, • Decorator, • Composite, • State, • Adapter, • Façade, • Bridge, • Flyweight, • Abstract Factory, • Factory method, • ... Still: • They have a context which may need to be adapted. • They are abstractions, not out of the box components.
  32. 32. ARCHITECTURAL PATTERNS• Bucshmann et al. series of Pattern Oriented Software Architecture• Higher-level concerns: architecture v.s. design.• Decoupled from OO compared to the GoF book (different domain). • Layers, • Reflection, • Pipes and Filters, • Whole-part, • Blackboard, • Master-slave, • Broker, • Proxy, • Model-View-Controller, • Command Processor, • Presentation-Abstraction-Control, • View Handler, • Microkernel, • ...
  33. 33. DOMAIN-SPECIFICThere are several books and pattern languages that focus onspecific domains such as: • Distributed systems, • Documentation, • Adaptive systems, • Frameworks, • Requirements engineering, • Interaction design, • Sociology, • Pedagogical, • Psychology, • ...Some are even about patterns themselves: • A Pattern Language for Patern Writing, • Meta-Patterns.
  34. 34. ANATOMY OF A PATTERNName. Usually a “catchy” noun that restrict the pattern to a narrow list ofdescribes what the pattern “builds.” specifics.Aliases. Also known as... Resulting Context. Include the new problems that appear as a result of applyingSketch. A metaphorical figure. the pattern that may require new patternsContext. Describe the setting for the for their resolution.problem. Include a description of the target Rationale. Explain the rationale behind theuser. solution. Convince the reader. Tell stories!Forces. Why the problem is not trivial. Share your expertise.Discuss other possible solutions and why Known Uses. Briefly list or describe placesthey won’t work. where the pattern is used.Problem. Unbiased by the solution. Related Patterns. Briefly describe anySolution. Include enough detail so the user related patterns and their relationships tocan implement the solution, but don’t this pattern.
  35. 35. EXTENDED ANATOMY...Name. Usually a “catchy” noun that restrict the pattern to a narrow list ofdescribes what the pattern “builds.” specifics.Aliases. Also known as... Resulting Context. Include the new problems that appear as a result of applyingSketch. A metaphorical figure. the pattern that may require new patternsContext. Describe the setting for the for their resolution.problem. Include a description of the target Rationale. Explain the rationale behind theuser. solution. Convince the reader. Tell stories!Forces. Why the problem is not trivial. Share your expertise.Discuss other possible solutions and why Known Uses. Briefly list or describe placesthey won’t work. where the pattern is used.Problem. Unbiased by the solution. Related Patterns. Briefly describe anySolution. Include enough detail so the user related patterns and their relationships tocan implement the solution, but don’t this pattern.
  36. 36. EXAMPLE
  37. 37. OBSERVER PATTERNAlso known asSubject Observer, Publish-Subscribe, Callback.IntentDefine a one-to-many dependency between objects so that whenone object (called the subject) changes state, all its dependents(called the observers) are notified and updated automatically.MotivationThe need to maintain consistency between related objects withoutmaking classes tightly coupled
  38. 38. SKETCH(doesn’t know the observers)
  39. 39. APPLICABILITYUse the Observer pattern in any of the following situations:• When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.• When a change to one object requires changing others• When an object should be able to notify other objects without making assumptions about those objects
  40. 40. STRUCTURE abstract classabstract class or interface
  41. 41. PARTICIPANTSSubject • Keeps track of its observers • Provides an interface for attaching and detaching Observer objectsObserver • Defines an interface for update notificationConcreteSubject • The object being observed • Stores state of interest to ConcreteObserver objects • Sends a notification to its observers when its state changesConcreteObserver • The observing object • Stores state that should stay consistent with the subjects • Implements the Observer update interface to keep its state consistent with the subjects
  42. 42. COLLABORATIONS
  43. 43. CONSEQUENCES+ Minimal coupling between the Subject and the Observer • Can reuse subjects without reusing their observers and vice versa • Observers can be added without modifying the subject • All subject knows is its list of observers • Subject does not need to know the concrete class of an observer, just that each observer implements the update interface • Subject and observer can belong to different abstraction layers+ Support for event broadcasting • Subject sends notification to all subscribed observers • Observers can be added/removed at any time– Possible cascading of notifications • Observers are not necessarily aware of each other and must be careful about triggering updates– Simple update interface requires observers to deduce changed item
  44. 44. IMPLEMENTATION• How does the subject keep track of its observers? • Array, linked list• What if an observer wants to observe more than one subject? • Have the subject tell the observer who it is via the update interface• Who triggers the update? • The subject whenever its state changes • The observers after they cause one or more state changes • Some third party object(s)• Make sure the subject updates its state before sending out notifications• How much info about the change should the subject send to the observers? • Push Model - Lots • Pull Model - Very Little
  45. 45. IMPLEMENTATION• Can the observers subscribe to specific events of interest? • If so, its publish-subscribe• Can an observer also be a subject? • Yes!• What if an observer wants to be notified only after several subjects have changed state? • Use an intermediary object which acts as a mediator • Subjects send notifications to the mediator object which performs any necessary processing before notifying the observers
  46. 46. KNOWN USES• Smalltalk Model/View/Controller user interface framework • Model = Subject • View = Observer • Controller is whatever object changes the state of the subject• Java 1.1 AWT/Swing Event Model
  47. 47. RELATED PATTERNS• Mediator. To encapsulate complex update semantics.
  48. 48. JAVA BUILT-IN SUPPORTinterface java.util.Observer• void update(Observable o, Object arg)class java.util.Observable (=Subject)• void addObserver(Observer o)• void deleteObserver(Observer o)• void setChanged()• void notifyObservers(Object arg)
  49. 49. A CONCRETE SUBJECT JAVApublic class ConcreteSubject extends Observable ... private String name; private float price; public ConcreteSubject(String name, float price) { this.name = name; this.price = price; } public String getName() { return name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(price); }
  50. 50. A CONCRETE OBSERVER JAVApublic class ConcreteObserver implements Observer ... private float price; public ConcreteObserver() { price = 0; } public void update(Observable obj, Object arg) { price = (Float) arg; } public getPrice() { return price; }
  51. 51. TEST SCENARIO JAVA@Testpublic void test1() { ConcreteSubject s = new ConcreteSubject("Corn", 1.29f); ConcreteObserver o = new ConcreteObserver(); s.addObserver(o); s.setPrice(4.57f); assertEquals(4.57f, o.getPrice());}
  52. 52. ?

×