Software Patterns


Published on

Introducing Software Architecture and Design Patterns in a nutshell.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Low hardware traps sensor input reading electrical signals from a wire High user-visible functionality high-level policies such as phone tariffs
  • Software Patterns

    1. 1. Software Patterns Sudarsun Santhiappan Director – Research & Development Burning Glass Technologies Chennai 600010
    2. 2. Coverage <ul><li>Object Oriented Thinking
    3. 3. Diagrammatic Representation
    4. 4. Software Architecture
    5. 5. Architecture Patterns
    6. 6. Design Patterns </li></ul>
    7. 7. Objectives <ul><li>Open a window to the architecture and design patterns world, explain why are they needed and where did they came from, and give some examples and real world tastes of chosen Design Pattern and Architectures
    8. 8. Not a programming language oriented lecture, we will mainly discuss the paradigms and uses with examples in various programming languages. </li></ul>
    9. 9. Programming Paradigms.. <ul><li>Block Programming
    10. 10. Procedural Programming
    11. 11. Object Oriented Programming </li><ul><li>Polymorphism + Late Binding (some) + Encapsulation (some) + Inheritance </li></ul><li>Component Oriented </li><ul><li>Polymorphism + Really Late Binding + Real, Enforced Encapsulation + Interface Inheritance + Binary Reuse </li></ul><li>SOA </li></ul>
    12. 12. Types of S/W Patterns <ul><li>design patterns (software design) [Buschmann-POSA] </li><ul><li>architectural (systems design)
    13. 13. design (micro-architectures) [Gamma-GoF]
    14. 14. idioms (low level) </li></ul><li>analysis patterns (recurring & reusable analysis models) [Flower]
    15. 15. organization patterns (structure of organizations/projects)
    16. 16. process patterns (software process design)
    17. 17. domain-specific patterns </li></ul>
    18. 18. Overview of the UML <ul><li>The UML is a language for </li><ul><li>visualizing
    19. 19. specifying
    20. 20. constructing
    21. 21. documenting </li></ul></ul>the artifacts of a software-intensive system
    22. 22. Overview of the UML <ul><li>Modeling elements
    23. 23. Relationships
    24. 24. Extensibility Mechanisms
    25. 25. Diagrams </li></ul>
    26. 26. Modeling Elements <ul><li>Structural elements </li><ul><li>class, interface, collaboration, use case, active class, component, node </li></ul><li>Behavioral elements </li><ul><li>interaction, state machine </li></ul><li>Grouping elements </li><ul><li>package, subsystem </li></ul><li>Other elements </li><ul><li>note </li></ul></ul>
    27. 27. Relationships <ul><li>Dependency
    28. 28. Association
    29. 29. Generalization
    30. 30. Realization </li></ul>
    31. 31. Extensibility Mechanisms <ul><li>Stereotype
    32. 32. Tagged value
    33. 33. Constraint </li></ul>
    34. 34. Models, Views, and Diagrams Activity Diagrams A model is a complete description of a system from a particular perspective Models Use Case Diagrams Use Case Diagrams Use Case Diagrams Scenario Diagrams Scenario Diagrams Collaboration Diagrams State Diagrams State Diagrams Component Diagrams Component Diagrams Component Diagrams Deployment Diagrams State Diagrams State Diagrams Object Diagrams Scenario Diagrams Scenario Diagrams Statechart Diagrams Use Case Diagrams Use Case Diagrams Sequence Diagrams State Diagrams State Diagrams Class Diagrams
    35. 35. Diagrams <ul><li>A diagram is a view into a model </li><ul><li>Presented from the aspect of a particular stakeholder
    36. 36. Provides a partial representation of the system
    37. 37. Is semantically consistent with other views </li></ul><li>In the UML, there are nine standard diagrams </li><ul><li>Static views: use case, class, object, component, deployment
    38. 38. Dynamic views: sequence, collaboration, statechart, activity </li></ul></ul>
    39. 39. Use Case Diagram <ul><li>Captures system functionality as seen by users </li></ul>
    40. 40. Use Case Diagram <ul><li>Captures system functionality as seen by users
    41. 41. Built in early stages of development
    42. 42. Purpose </li><ul><li>Specify the context of a system
    43. 43. Capture the requirements of a system
    44. 44. Validate a system’s architecture
    45. 45. Drive implementation and generate test cases </li></ul><li>Developed by analysts and domain experts </li></ul>
    46. 46. Class Diagram <ul><li>Captures the vocabulary of a system </li></ul>
    47. 47. Class Diagram <ul><li>Captures the vocabulary of a system
    48. 48. Built and refined throughout development
    49. 49. Purpose </li><ul><li>Name and model concepts in the system
    50. 50. Specify collaborations
    51. 51. Specify logical database schemas </li></ul><li>Developed by analysts, designers, and implementers </li></ul>
    52. 52. Object Diagram <ul><li>Captures instances and links </li></ul>
    53. 53. Object Diagram <ul><li>Shows instances and links
    54. 54. Built during analysis and design
    55. 55. Purpose </li><ul><li>Illustrate data/object structures
    56. 56. Specify snapshots </li></ul><li>Developed by analysts, designers, and implementers </li></ul>
    57. 57. Component Diagram <ul><li>Captures the physical structure of the implementation </li></ul>
    58. 58. Component Diagram <ul><li>Captures the physical structure of the implementation
    59. 59. Built as part of architectural specification
    60. 60. Purpose </li><ul><li>Organize source code
    61. 61. Construct an executable release
    62. 62. Specify a physical database </li></ul><li>Developed by architects and programmers </li></ul>
    63. 63. Deployment Diagram <ul><li>Captures the topology of a system’s hardware </li></ul>
    64. 64. Deployment Diagram <ul><li>Captures the topology of a system’s hardware
    65. 65. Built as part of architectural specification
    66. 66. Purpose </li><ul><li>Specify the distribution of components
    67. 67. Identify performance bottlenecks </li></ul><li>Developed by architects, networking engineers, and system engineers </li></ul>
    68. 68. Sequence Diagram <ul><li>Captures dynamic behavior (time-oriented) </li></ul>
    69. 69. Sequence Diagram <ul><li>Captures dynamic behavior (time-oriented)
    70. 70. Purpose </li><ul><li>Model flow of control
    71. 71. Illustrate typical scenarios </li></ul></ul>
    72. 72. Collaboration Diagram <ul><li>Captures dynamic behavior (message-oriented) </li></ul>
    73. 73. Collaboration Diagram <ul><li>Captures dynamic behavior (message-oriented)
    74. 74. Purpose </li><ul><li>Model flow of control
    75. 75. Illustrate coordination of object structure and control </li></ul></ul>
    76. 76. Statechart Diagram <ul><li>Captures dynamic behavior (event-oriented) </li></ul>
    77. 77. Statechart Diagram <ul><li>Captures dynamic behavior (event-oriented)
    78. 78. Purpose </li><ul><li>Model object lifecycle
    79. 79. Model reactive objects (user interfaces, devices, etc.) </li></ul></ul>
    80. 80. Activity Diagram <ul><li>Captures dynamic behavior (activity-oriented) </li></ul>
    81. 81. Activity Diagram <ul><li>Captures dynamic behavior (activity-oriented)
    82. 82. Purpose </li><ul><li>Model business workflows
    83. 83. Model operations </li></ul></ul>
    84. 84. Architecture and the UML Design View Implementation View Process View Deployment View Organization Package, subsystem Dynamics Interaction State machine Components Classes, interfaces, collaborations Active classes Nodes Use Case View Use cases
    85. 85. Software engineering process <ul><li>A set of partially ordered steps intended to reach a goal. In software engineering the goal is to build a software product or to enhance an existing one . </li></ul><ul><li>Architectural process </li><ul><li>Sequence of activities that lead to the production of architectural artifacts: </li><ul><li>A software architecture description
    86. 86. An architectural prototype </li></ul></ul></ul>
    87. 87. System Architecture Logical View Implementation View Programmers Software management Process View Deployment View System topology Delivery, installation Communication System engineering Conceptual Physical Use Case View Conceptual Physical End-user Functionality Performance Scalability Throughput System integrators
    88. 88. Pattern Oriented Software Architecture Patterns for Software Architecture, Distributed Systems and Resource Management <ul><li>Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal. Pattern-oriented Software Architecture: System of Patterns Vol 1. John Wiley and Sons Ltd. 1996.
    89. 89. Frank Buschmann, Douglas Schmidt, Michael Stal, Hans Rohnert. Pattern-oriented Software Architecture Vol 2: Patterns for Concurrent and Networked Objects. John Wiley and Sons Ltd. 2000.
    90. 90. Michael Kircher, Prashant Jain. Pattern-Oriented Software Architecture: Patterns for Distributed Services and Components. John Wiley and Sons Ltd. 2004. </li></ul>Three types of patterns (Buschmann et al.): <ul><li>Architectural Patterns </li><ul><li>An architectural pattern expresses a fundamental structural organization for software systems or schema for software systems. It provides a set of predefined subsystems, specifies their responsibilities, and includes rules and guidelines for organizing the relationships between them. </li></ul><li>Design Patterns </li><ul><li>A design pattern provides a scheme for refining the subsystems or components of a software system, or the relationships between them. It describes commonly recurring structure of communicating components that solve a design problem within a particular context. </li></ul><li>Idioms </li><ul><li>An idiom is a low-level pattern specific to a programming language. An idiom describes how to implement particular aspects of components or the relationships between them using the features of the given language. </li></ul></ul>
    91. 91. Architecture - Definition <ul><li>Highest level representation of a system
    92. 92. How a big system could be broken down into smaller components ?
    93. 93. Shared understanding of a system
    94. 94. How major components fit together ?
    95. 95. How components interact ? </li></ul>
    96. 96. Example: Nokia MITA <ul><li>Mobile Internet Technical Architecture </li></ul>Intranet (WLAN)/Bluetooth Web domain Internet xDSL PSTN Mobile networks GSM EDGE WCDMA Mobile domain WLAN /Bluetooth Bluetooth =Server
    97. 97. Architecture <ul>Software architecture encompasses the set of significant decisions about the organization of a software system <ul><li>selection of the structural elements and their interfaces by which a system is composed
    98. 98. behavior as specified in collaborations among those elements
    99. 99. Composition of these structural and behavioral elements into larger subsystem
    100. 100. architectural style that guides this organization </li></ul></ul>
    101. 101. Architecture Characteristics <ul><li>usage
    102. 102. functionality
    103. 103. performance
    104. 104. resilience
    105. 105. reuse
    106. 106. comprehensibility
    107. 107. economic and technology constraints and trade offs
    108. 108. aesthetic concerns </li></ul>
    109. 109. Who are the architects? <ul><li>Experience </li><ul><li>software development
    110. 110. domain </li></ul><li>Pro-active, goal oriented
    111. 111. Leadership, authority
    112. 112. Architecture team </li><ul><li>balance </li></ul></ul>
    113. 113. Architect <ul><li>Not just a top level designer </li><ul><ul><li>Need to ensure feasibility </li></ul></ul><li>Not the project manager </li><ul><ul><li>But “joined at the hip” </li></ul></ul><li>Not a technology expert </li><ul><ul><li>Purpose of the system, “fit”, </li></ul></ul><li>Not a lone scientist </li><ul><ul><li>Communicator </li></ul></ul></ul>
    114. 114. Software Architecture Team Charter <ul><li>Defining the architecture of the software
    115. 115. Maintaining the architectural integrity of the software
    116. 116. Assessing technical risks related to the software design
    117. 117. Proposing the order and contents of the successive iterations
    118. 118. Consulting services
    119. 119. Assisting marketing for future product definition
    120. 120. Facilitating communications between project teams </li></ul>
    121. 121. Architecture is making decisions The life of a software architect is a long (and sometimes painful) succession of suboptimal decisions made partly in the dark.
    122. 122. Architectural design <ul><li>Identify, select, and validate “architecturally significant” elements
    123. 123. Not everything is architecture </li><ul><li>Main “business” classes
    124. 124. Important mechanisms
    125. 125. Processors and processes
    126. 126. Layers and subsystems
    127. 127. Interfaces </li></ul><li>Produce a Software Architecture Documen </li></ul>
    128. 128. Architectural design workflow <ul><li>Select scenarios: criticality and risk
    129. 129. Identify main classes and their responsibility
    130. 130. Distribute behavio r on classes
    131. 131. Structure in subsystems, layers, define interfaces
    132. 132. Define distribution and concurrency
    133. 133. Implement architectural prototype
    134. 134. Derive tests from use cases
    135. 135. Evaluate architecture </li></ul>Iterate Use case view Logical view Deployment view Implementation view Process view
    136. 136. Patterns <ul><li>A pattern is a solution to a problem in a context
    137. 137. A pattern codifies specific knowledge collected from experience in a domain
    138. 138. All well-structured systems are full of patterns </li><ul><li>Idioms
    139. 139. Design patterns
    140. 140. Architectural patterns </li></ul></ul>
    141. 141. Patterns - Definition <ul><li>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 .
    142. 142. Each pattern is a three-part rule , which expresses a relation between a certain context , a problem , and a solution .
    143. 143. GoF: The design patterns are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context </li></ul>
    144. 144. Why Patterns? <ul><li>Patterns can be used by programmers, designers, and architects who are building applications and who want to improve either their understanding of architectural issues or their communication about them. (Fowler)
    145. 145. Patterns are common solutions to recurring problems. If you have worked in applications for a while, you may well know most of them. They are industry’s old ideas . If you are new , pattern book can help you learn about those techniques. If you are familiar with the techniques, pattern book can help you communicate and teach them to others. An important part of patterns is trying to build a common vocabulary for communication . (Fowler)
    146. 146. Patterns constitute an effort to build on the collective experience of skilled designers and software engineers. (Buschmann et al.)
    147. 147. Experts already have solutions to many recurring design problems . (Buschmann et al.)
    148. 148. Patterns capture proven solutions in an easily-available and, hopefully, well-written form (Buschmann et al.)
    149. 149. Patterns support both novices and experts in software development. (Buschmann et al.) </li></ul>
    150. 150. Architectural Patterns
    151. 151. Architectural patterns <ul><li>Distributed  Layered
    152. 152. Event-driven  MVC
    153. 153. Frame-based  IR-centric
    154. 154. Batch  Subsumption
    155. 155. Pipes and filters  Disposable
    156. 156. Repository-centric
    157. 157. Blackboard
    158. 158. Interpreter
    159. 159. Rule-based </li></ul>
    160. 160. Model View Controller <ul><li>The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes
    161. 161. The controller changes the model
    162. 162. The View Listens to Model
    163. 163. Process Control! </li></ul>
    164. 164. What is the Layers Pattern? <ul><li>Architectural pattern that helps to structure applications that can be decomposed into groups of subtasks in which each group of subtasks is at a particular level of abstraction.
    165. 165. What is high? What is low?
    166. 166. Flow </li><ul><li>requests from higher layer to lower layer
    167. 167. answers from lower layer to higher layer
    168. 168. incoming data or event notification from low to high </li></ul></ul>
    169. 169. Things to Take Care of... <ul><li>Late source code changes should not ripple
    170. 170. Interfaces should be stable
    171. 171. Interfaces may be prescribed by a standards body
    172. 172. Parts of the system should be exchangeable
    173. 173. Design for change!
    174. 174. May be necessary to build other systems at a later date with same low-level issues
    175. 175. Similar responsibilities should be grouped to help understandability and maintainability
    176. 176. No standard component granularity
    177. 177. Complex components may need further decomposition </li></ul>
    178. 178. More... <ul><li>Crossing component boundaries may impede performance </li><ul><li>substantial amount of data transferred over several boundaries </li></ul><li>The system will be built by actual human beings </li><ul><li>Work must be subdivided along clear boundaries
    179. 179. Architecture influences team structure and vice versa </li></ul></ul>
    180. 180. Solution <ul><li>Structure the system into an appropriate number of layers
    181. 181. Think of lowest level as Layer 1; highest Layer N
    182. 182. This gives a conceptual view – not marching orders regarding sequence of further design
    183. 183. Within a layer, all subcomponents work at the same level of abstraction
    184. 184. Most of what Layer J provides is composed of services provided by Layer J-1, combined in a meaningful way for the application. </li></ul>
    185. 185. Illustration
    186. 186. Implementation <ul><li>Define which of the abstraction criteria you will use
    187. 187. Determine the number of abstraction levels according to your criterion
    188. 188. Name the layers and assign tasks to each of them
    189. 189. Specify the services
    190. 190. Refine the layering </li></ul><ul><ul><li>repeat steps 1-4 until natural, stable layering evolves
    191. 191. Finding layers is not orderly – yo-yo development </li></ul></ul><ul><li>Specify an interface for each layer </li></ul>
    192. 192. Implementation <ul><li>Structure individual layers
    193. 193. Specify communication between adjacent layers </li></ul><ul><ul><li>push/pull </li></ul></ul><ul><li>Decouple adjacent layers </li></ul><ul><ul><li>t op-down: J+1 knows about J; J can ignore J+1
    194. 194. bottom-up: </li><ul><li>can use callbacks
    195. 195. can decouple the upper from the lower somewhat </li></ul></ul></ul><ul><li>Design an error-handling strategy </li></ul>
    196. 196. Some Applications <ul><li>Virtual Machines
    197. 197. APIs
    198. 198. Information Systems – Lower Layer is DB </li><ul><li>Presentation
    199. 199. Application Logic
    200. 200. Domain Layer
    201. 201. Database </li></ul><li>Operating Systems </li></ul>
    202. 202. SOA <ul><li>SOA is an architectural style whose goal is to achieve loose coupling among interacting software agents.
    203. 203. A service is a unit of work done by a service provider to achieve desired end results for a service consumer
    204. 204. in SOA, services are the mechanism by which needs and capabilities are brought together. </li></ul>
    205. 205. SOA - Principles <ul><li>Visibility – the ability for a service consumer to “see” a service provider (Awareness, willingness and Reachability)
    206. 206. Interaction - the activity of using a capability. (usually message exchange - by contracts, constraints and policies, for example Web Service Description Language)
    207. 207. Effect – the result of an interaction
    208. 208. SOAP: Simple Object Access Protocol
    209. 209. WSDL: Web Service Description Language </li></ul>
    210. 210. SOA - example
    211. 211. Idioms
    212. 212. Guard <ul><li>Problem </li><ul><li>Want to tie key scoped behaviors to actual program scopes </li><ul><li>e.g., program trace, resource acquisition/release, locking </li></ul><li>However, tying functions to functions is error-prone </li><ul><li>e.g., forgetting the release call, exceptional return paths </li></ul></ul><li>Solution </li><ul><li>Design a special adapter class whose constructor and destructor call the key scope entry and exit behaviors
    213. 213. Create a guard object on the program call stack (in a scope) </li></ul><li>Context limitations </li><ul><li>Mainly limited to languages with constructor/destructor </li></ul></ul>
    214. 214. Design Patterns
    215. 215. What are design patterns? <ul><li>The Beginning - “Gang of four” (Gama et al 1995) </li></ul><ul><li>What's the difference between an architecture and a Design patterns?
    216. 216. Patterns sub types: </li><ul><li>Creational
    217. 217. Structural
    218. 218. Behavioral </li></ul></ul>
    219. 219. Design Patterns Catalog
    220. 220. Template Method Pattern Intent / Applicability <ul><li>Intent </li><ul><li>Define the skeleton of an algorithm, deferring some steps to subclasses.
    221. 221. Template Method lets subclasses redefine certain steps of an algorithm, without changing the algorithm’s structure. </li></ul><li>Applicability – Use Template Method Pattern… </li><ul><li>To implement the invariant part of an algorithm, and leave it up to subclasses to implement the part that can vary.
    222. 222. When common code in subclasses should be factored and localized in a common base class to avoid code duplication.
    223. 223. To control extensions to subclasses. (Hook operations) </li></ul></ul>
    224. 224. Template Method Pattern Participants <ul><li>AbstractClass </li><ul><li>Defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
    225. 225. Implements a template method defining the skeleton of an algorithm. It calls primitive operations as well as other operations in the AbstractClass (or other classes). </li></ul></ul><ul><li>ConcreteClass </li></ul><ul><ul><li>Implements primitive operations to carry out subclass-specific steps of the algorithm. </li></ul></ul>Note: Some concrete AbstractClass methods can also be defined. Hollywood Principle – “Don’t call us, we’ll call you.” => Parent class calls operations of subclass.
    226. 226. Strategy Pattern Intent / Applicability <ul><li>Intent </li><ul><li>Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. </li></ul><li>Applicability – Use Strategy Pattern when… </li><ul><li>Many related classes differ only in their behavior.
    227. 227. You need different variants of an algorithm. For example, defining different algorithms based on space-time tradeoffs.
    228. 228. An algorithm uses data that a client shouldn’t know about.
    229. 229. A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead, move related conditional branches into their own Strategy class. </li></ul></ul>
    230. 230. Strategy Pattern - Participants <ul><li>Strategy </li><ul><li>Declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy. </li></ul><li>ConcreteStrategy </li><ul><li>Implements the algorithm using the Strategy interface. </li></ul><li>Context </li><ul><li>Is configured with a ConcreteStrategy object
    231. 231. Maintains a reference to a Strategy object
    232. 232. May define an interface that lets Strategy access its data. </li></ul></ul>
    233. 233. Strategy Pattern - Participants Show code in RealWorld Example <ul><li>Strategy </li><ul><li>SortStrategy </li></ul><li>ConcreteStrategy </li><ul><li>QuickSort
    234. 234. ShellSort
    235. 235. MergeSort </li></ul><li>Context </li><ul><li>SortedList </li></ul></ul>Picture & Example from: http://
    236. 236. Strategy – Consequences <ul><li>Good Consequences </li><ul><li>Good for families of related algorithms. Inheritance can help factor out common functionality of algorithms.
    237. 237. Alternative to subclassing which allows the developer to vary the algorithm independent of its context.
    238. 238. Strategies eliminate conditional statements.
    239. 239. Provide different implementations of the same behavior. Example: Sorting is goal, but many ways to sort. </li></ul><li>Drawbacks </li><ul><li>Clients must be aware of different strategies.
    240. 240. Communication overhead between Strategy and Context – some concrete strategies may not need all the parameters passed into them.
    241. 241. Increased number of objects. See Flyweight pattern for an approach to solve this. </li></ul></ul>
    242. 242. Iterator <ul><li>Intent </li><ul><li>Provide a means to Iterate through a series of nodes in specific way(s) </li></ul><li>Motivation </li><ul><li>To traverse lists of information without having to know anything too specific about the objects
    243. 243. To implement multiple algorithms to traverse those nodes. </li></ul></ul>
    244. 244. Class Diagram
    245. 245. Iterator:Implementation <ul><li>Who Controls the Iteration? </li><ul><li>External Iterator </li><ul><li>Client controls iteration
    246. 246. Client must explicitly request next() on each node </li></ul><li>Internal Iterator </li><ul><li>Iterator controls iteration
    247. 247. Client hands an operation to the Iterator, Iterator tells every child in the aggregate to perform it. </li></ul></ul></ul>
    248. 248. Implementation Benefits <ul><li>External Iterator </li><ul><li>More flexible than Internal. Can compare 2 collections easily </li></ul><li>Internal Iterator </li><ul><li>Easier to use, as they define the iteration logic for you. Makes portability easier. </li></ul></ul>
    249. 249. Who defines the traversal Algorithm? <ul><li>Algorithm can be held by a class outside of the Iterator. It could be held by the aggregate can hold it. </li><ul><li>Called “the cursor.”
    250. 250. Allows the algorithm to access private members of the aggregate (and not break encapsulation) </li></ul><li>Algorithm is held by the iterator </li><ul><li>Allows algorithms to be swapped out easily. </li></ul></ul>
    251. 251. How Robust is the Iterator? <ul><li>If an iterator is robust it </li><ul><li>Will allow for removal of nodes in the middle of traversal.
    252. 252. It does this through registering the iterator with the aggregate. If any nodes are removed, it is notified. </li></ul></ul>
    253. 253. Additional Iterator Operations <ul><li>All come with first, next, isdone, and currentItem
    254. 254. Previous </li><ul><li>Goes to the previous node that was iterated
    255. 255. Can be helpful in certain situations </li></ul><li>SkipTo </li><ul><li>Skips to a certain node.
    256. 256. Goes to a node matching specific criteria </li></ul></ul>
    257. 257. Observer Pattern <ul><li>Behavioral Pattern
    258. 258. one-to-many dependency model, so that when one object changes state, all its dependents are notified and updated automatically without coupling the notifying object to the objects that are notified. </li></ul>Example: <ul><li>Button expose a clicked event that encapsulate click state, thus publish himself as an observable. Clients that are interested in this event register to it, thus becomes observers.
    259. 259. Observer and observable are bonded in a contract and can be completely loosely coupled from one another. </li></ul>
    260. 260. Singleton design pattern <ul><li>Creational pattern
    261. 261. ensure that a class has only one instance, and to provide a global point of access to it </li></ul>Example: Class SomeClass { static SomeClass singleTonInstance = null; static SomeClass GetInstance() { if(singleTonInstance == null) singleTonInstance = new SomeClass() return singleTonInstance; } }
    262. 262. Factory design patterns (Abstract Lightweight) <ul><li>Creational pattern
    263. 263. Can be given to client (abstract), pass construction parameters or read creation types from configuration or system environment
    264. 264. Can use object pool (Lightweight) </li></ul>
    265. 265. Factory design pattern - example abstract class GUIFactory { public static GUIFactory getFactory() { int sys = readFromConfigFile(&quot;OS_TYPE&quot;); return sys == 0 ? new WinFactory() : new OSXFactory(); } public abstract Button createButton(); } class WinFactory:GUIFactory { public override Button createButton() { return new WinButton(); } } class MacFactory:GUIFactory { public override Button createButton(){ return new MacButton(); } } abstract class Button { public string caption; public abstract void paint(); }
    266. 266. class WinButton:Button { public override void paint() { // paint a button with Win API…} } class MacButton:Button { public override void paint() { // paint a button Mac style… } } class Application { static void Main(string[] args) { GUIFactory aFactory = GUIFactory.getFactory(); Button aButton = aFactory.createButton(); aButton.caption = &quot;Play&quot;; aButton.paint(); } } Factory design pattern - example
    267. 267. Façade design pattern <ul><li>Structural Pattern
    268. 268. Provide a unified interface to a set of interfaces in a subsystem without damaging the genric form of the sub system. </li></ul>
    269. 269. Decorator pattern <ul><li>Structural Pattern
    270. 270. Avoid excessive sub-classing and gain run time flexibility
    271. 271. Example: </li></ul>Java.IO package BufferedReader br =  new  BufferedReader( new  InputStreamReader(            new  FileInputStream(inFile))); All derives from abstract io.Reader
    272. 272. Example
    273. 273. Example // the Window interface interface Window { public void draw(); // draws the Window public String getDescription(); // returns a description of the Window } // implementation of a simple Window without any scrollbars class SimpleWindow implements Window { public void draw() { // draw window } public String getDescription() { return &quot;simple window&quot;; } } // abstract decorator class - note that it implements Window abstract class WindowDecorator implements Window { protected Window decoratedWindow; // the Window being decorated public WindowDecorator (Window decoratedWindow) { this.decoratedWindow = decoratedWindow; } }
    274. 274. Example // the first concrete decorator which adds vertical scrollbar functionality class VerticalScrollBarDecorator extends WindowDecorator { public VerticalScrollBarDecorator (Window decoratedWindow) { super(decoratedWindow); } public void draw() { drawVerticalScrollBar(); decoratedWindow.draw(); } private void drawVerticalScrollBar() { // draw the vertical scrollbar } public String getDescription() { return decoratedWindow.getDescription() + &quot;, including vertical scrollbars&quot;; } } // the second concrete decorator which adds horizontal scrollbar functionality class HorizontalScrollBarDecorator extends WindowDecorator { public HorizontalScrollBarDecorator (Window decoratedWindow) { super(decoratedWindow); } public void draw() { drawHorizontalScrollBar(); decoratedWindow.draw(); } private void drawHorizontalScrollBar() { // draw the horizontal scrollbar } public String getDescription() { return decoratedWindow.getDescription() + &quot;, including horizontal scrollbars&quot;; } }
    275. 275. Example public class DecoratedWindowTest { public static void main(String[] args) { // create a decorated Window with // horizontal and vertical scrollbars Window decoratedWindow = new HorizontalScrollBarDecorator ( new VerticalScrollBarDecorator( new SimpleWindow())); // print the Window's description System.out.println(decoratedWindow.getDescription()); } } Output: &quot;simple window, including vertical scrollbars, including horizontal scrollbars&quot;
    276. 276. Strategy Pattern <ul><li>Behavioral Pattern
    277. 277. defines a family of interchangeable encapsulated algorithms that receives the same input type and provides the same output type in different manners that can be determined in run-time. </li></ul>static void Main( { SortedList studentRecords = new SortedList(); studentRecords.Add(&quot;Samual&quot;); studentRecords.Add(&quot;Jimmy&quot;); studentRecords.Add(&quot;Sandra&quot;);      studentRecords.SetSortStrategy(new QuickSort()); studentRecords.Sort(); studentRecords.SetSortStrategy(new ShellSort()); studentRecords.Sort();   }
    278. 278. Strategy Pattern - example abstract class SortStrategy { public abstract void Sort(ArrayList list) } class QuickSort : SortStrategy { public override void Sort(ArrayList list) {       list.Sort(); // Default is Quicksort        } } class ShellSort : SortStrategy { public override void Sort(ArrayList list) {       //list.ShellSort(); not-implemented       }   }
    279. 279. class SortedList { private ArrayList list = new ArrayList(); private SortStrategy sortstrategy; public void SetSortStrategy(SortStrategy sortstrategy) {       this.sortstrategy = sortstrategy; } public void Add(string name) {       list.Add(name); }      public void Sort() {      sortstrategy.Sort(list);    } } Strategy Pattern - example
    280. 280. Proxy Pattern <ul><li>Intent </li><ul><li>Provide a surrogate or placeholder for another object to control access to it </li></ul><li>Other Names </li><ul><li>Surrogate </li></ul></ul>
    281. 281. Proxy Pattern: Applicability <ul><li>Forms of the proxy pattern: </li><ul><li>Remote proxy – Provides a local representative for an object in a different address space.
    282. 282. Virtual Proxy – Creates expensive objects on demand.
    283. 283. Protection Proxy – Controls access to the original object.
    284. 284. Smart References – Additional functionality pointers. </li><ul><li>Smart Pointers
    285. 285. Initial loading of persistent objects.
    286. 286. Object locking. </li></ul></ul></ul>
    287. 287. Proxy Pattern: Participants <ul><li>Proxy </li><ul><li>Maintains a reference to the real subject.
    288. 288. Provide identical interface to Subject so the Proxy can be substituted.
    289. 289. Controls access to the real subject and may be responsible for creating and deleting the real subject. </li></ul><li>RealSubject </li><ul><li>Defines the real object that the proxy represents. </li></ul><li>Subject </li><ul><li>Defines the common interface for RealSubject and Proxy so that the proxy to be used wherever a RealSubject is expected. </li></ul></ul>
    290. 290. Proxy Pattern: Structure
    291. 291. Proxy Pattern: Example class Image; class ImagePtr { public: ImagePtr(const char* file); virtual ~ImagePtr(); virtual Image* operator->(); virtual Image& operator*(); private: Image* _image; const char* _file; Image* LoadImage(); }; Image* ImagePtr::LoadImage(){ If (_image == 0 ) { _image = LoadAnImageFile(_file); } return _image; } Image* ImagePtr::operator->() { return LoadImage(); } Image& ImagePtr::operator*(){ return *LoadImage(); } To implement the Real Subject methods: ImagePtr image = ImagePtr(“aFile”); image->Draw(Point(50,100)); //(image.operator->())->Draw(Point(50,100))
    292. 292. Proxy Pattern: Consequences <ul><li>Each proxy introduces a level of indirection. This may result in hiding detail from the implementer. </li><ul><li>A remote Proxy can hide the fact that object resides in a different address space.
    293. 293. A Virtual Proxy can perform optimizations such as creation on demand.
    294. 294. Protection Proxy and Smart References can allow additional housekeeping tasks when object is accessed. </li></ul><li>Copy-On-Write </li><ul><li>This hides optimization in which an object is not copied until it’s attributes are modified. </li></ul></ul>
    295. 295. Proxy: Related Patterns <ul><li>Adapter </li><ul><li>Provides a different interface to an object. Since a proxy may deny request based on access, the interface is will be a subset. </li></ul><li>Decorator </li><ul><li>Similar implementation to proxy but has a different purpose. This adds responsibilities to an object rather than controlling access. </li></ul></ul>
    296. 296. Adapter Pattern <ul><li>a.k.a. Wrapper
    297. 297. Has both class and object forms
    298. 298. Adapts the interface of one class into that of an otherwise incompatible class
    299. 299. Use to: </li><ul><li>make use of a class with incompatible interface
    300. 300. create reusable class that will play nice with others
    301. 301. use several subclasses without having to subclass each one to adapt their interface (object form) </li></ul></ul>
    302. 302. Adapter Pattern <ul><li>Structure </li></ul>
    303. 303. Adapter Pattern <ul><li>Participants </li><ul><li>Target </li><ul><li>defines the domain-specific interface that Client uses </li></ul><li>Client </li><ul><li>collaborates with objects conforming to Target interface </li></ul><li>Adaptee </li><ul><li>defines existing interface that needs adapting </li></ul><li>Adapter </li><ul><li>adapts the interface of Adaptee to the Target interface </li></ul></ul><li>Collaborations </li><ul><li>Clients call operations on Adapter instance, which in turn calls the appropriate Adaptee operations </li></ul></ul>
    304. 304. Adapter Pattern <ul><li>Consequences </li><ul><li>Class form </li><ul><li>commits to a concrete Adaptee class, so won’t work if we want to adapt a class as well as subclasses (use object form)
    305. 305. Adapter can override Adaptee’s behavior
    306. 306. introduces only one object; no pointer indirection required </li></ul><li>Object form </li><ul><li>allows single Adapter to work with many Adaptee subclasses; can add functionality to all Adaptees at once
    307. 307. harder to override Adaptee behvarior – have to subclass Adaptee and make Adapter refer to the subclass </li></ul></ul></ul>
    308. 308. Adapter Pattern <ul><li>Other Issues </li><ul><li>How much work does Adapter do? </li><ul><li>simple: changing names of otherwise identical operations
    309. 309. complex: supporting new functionality </li></ul><li>Pluggable Adapters </li><ul><li>use interface adaptation to make class more reusable </li></ul><li>Two-way Adapters </li><ul><li>a class adapter conforms to both incompatible classes
    310. 310. use multiple inheritance </li></ul></ul></ul>
    311. 311. Adapter Pattern <ul><li>Implementation Issues </li><ul><li>Class adapters in C++ </li><ul><li>adapts publicly from Target and privately from Adaptee
    312. 312. Adapter is subtype of Target, not Adaptee </li></ul><li>Pluggable Adapters </li><ul><li>Find “narrow” interface – smallest subset of operations
    313. 313. Either: </li><ul><li>make operations abstract in Target for different Adapters to implement
    314. 314. put operations in abstract delegate class for different Adapters to subclass </li></ul></ul></ul></ul>
    315. 315. Adapter Pattern <ul><li>Related Patterns </li><ul><li>Bridge – similar structure, but meant to separate interface from its implementation, rather than change interface of existing object
    316. 316. Decorator – enhances object without changing its interface. Thus more transparent and supports recursive composition
    317. 317. Proxy – defines surrogate for another object without changing its interface </li></ul></ul>
    318. 318. Bridge Pattern <ul><li>a.k.a. Handle/Body
    319. 319. Decouples abstraction from its implementation
    320. 320. Use to: </li><ul><li>avoid binding abstraction to implementation (i.e. want to choose different implementations at runtime)
    321. 321. make both abstraction and implementations independently extensible
    322. 322. change implementation or abstraction without impacting clients, or hide them from clients
    323. 323. share implementation among clients without letting them know </li></ul></ul>
    324. 324. Bridge Pattern <ul><li>Structure: </li></ul>
    325. 325. Bridge Pattern <ul><li>Participants </li><ul><li>Abstraction </li><ul><li>defines abstraction’s interface
    326. 326. maintains reference to Implementor instance </li></ul><li>RefinedAbstraction </li><ul><li>extends interface defined by Abstraction </li></ul><li>Implementor </li><ul><li>defines interface for implementation classes
    327. 327. typically provides more primitive operations than Abstraction </li></ul><li>ConcreteImplementor </li><ul><li>implements Implementor interface </li></ul></ul><li>Collaborations </li><ul><li>Abstraction forwards client requests to its Implementor object </li></ul></ul>
    328. 328. Bridge Pattern <ul><li>Consequences </li><ul><li>decouples interface and implementation </li><ul><li>allows selecting implementation at runtime
    329. 329. avoids compilation dependencies on implementation </li></ul><li>improves extensibility </li><ul><li>Abstraction and Implementation can be extended independently </li></ul><li>hides implementation details from clients </li></ul></ul>
    330. 330. Bridge Pattern <ul><li>Implementation Issues </li><ul><li>for only one implementation, may not need abstract Implementor
    331. 331. how, where, and when to choose concrete Implementor? </li><ul><li>by Abstraction, in its constructor?
    332. 332. change at runtime?
    333. 333. by another object, like an Abstract Factory? </li></ul><li>sharing Implementors </li><ul><li>Handle/Body idiom </li></ul><li>multiple inheritance </li><ul><li>combines interface back with implementation </li></ul></ul></ul>
    334. 334. Bridge Pattern <ul><li>Related Patterns </li><ul><li>Abstract Factory can create and configure Bridges
    335. 335. Adapter makes existing unrelated classes work together; whereas Bridge is used in design in effort to avoid needing Adapters later </li></ul></ul>
    336. 336. Consumer/Producer <ul><li>Concurrency Pattern
    337. 337. This design pattern coordinates the concurrent production and consumption of information among producer and consumer objects that are working on different threads.
    338. 338. This pattern is used with some type of semaphore </li></ul>
    339. 339. Consumer/Producer - example static AutoResetEvent eventProducerDone = new AutoResetEvent(false); static AutoResetEvent eventConsumerDone = new AutoResetEvent(false); static int currentNum = 0; static void produce(object stateInfo) { eventProducerDone.Set(); while (true) { //wait for the consumer eventConsumerDone.WaitOne(); currentNum++; eventProducerDone.Set(); } }
    340. 340. static void Main(string[] args) { ThreadPool.QueueUserWorkItem(new WaitCallback(produce)); for (int i = 0; i < 20; i++) { eventProducerDone.WaitOne(); System.Diagnostics.Debug.WriteLine(currentNum); eventConsumerDone.Set(); } } Consumer/Producer - example
    341. 341. Top 10 Misconceptions <ul><li>(1) A pattern is a solution to a problem in a context.
    342. 342. Why isn’t this true? </li><ul><li>Patterns are applied to recurring problems (not one instance).
    343. 343. Patterns teach , so that the developer can tailor the solution to a variant of the problem.
    344. 344. Patterns have a name . </li></ul></ul>
    345. 345. Top 10 Misconceptions <ul><li>(2) Patterns are just jargon, rules, programming tricks, data structures, etc. </li><ul><li>The idea of patterns is old… experienced programmers used previous solutions on new problems.
    346. 346. What is new is naming them and writing them down.
    347. 347. One drawback (from personal experience) is to assume everyone knows the pattern. Design documentation should note the name of the design pattern used, but that shouldn’t be the extent of the documentation. </li></ul></ul>
    348. 348. Top 10 Misconceptions <ul><li>(3) Seen one, seen them all. </li><ul><li>Patterns are extremely diverse.
    349. 349. Don’t make assumptions about all patterns based on a few patterns. </li></ul></ul>
    350. 350. Top 10 Misconceptions <ul><li>(4) Patterns need tool or methodological support to be effective. </li><ul><li>Benefits of patterns (no tool or support needed!) </li><ul><li>Patterns capture expertise and make it accessible to non-experts.
    351. 351. Pattern names form a vocabulary which helps developers communicate.
    352. 352. Documenting the design with the patterns in use helps people understand the system more quickly.
    353. 353. Patterns facilitate restructuring a system whether or not it was designed with patterns in mind. </li></ul></ul></ul>
    354. 354. Top 10 Misconceptions <ul><li>(5) Patterns guarantee reusable software, higher productivity, world peace, etc. </li><ul><li>Patterns don’t guarantee anything.
    355. 355. Similar comments were made about object-oriented programming when it was introduced. </li></ul><li>(6) Patterns ‘generate’ whole architectures. </li><ul><li>Need human creativity to know how to apply and tailor a pattern for your given problem.
    356. 356. Need to fill in the “white space” between the patterns.
    357. 357. Through teaching / discussion, patterns may support “generativity” – helping the reader solve problems that the pattern doesn’t address explicitly. </li></ul></ul>
    358. 358. Top 10 Misconceptions <ul><li>(7) Patterns are for (object-oriented) design or implementation. </li><ul><li>Patterns capture expertise, but are not limited to design and implementation.
    359. 359. Patterns can be found in analysis, maintenance, testing, documentation, organizational structure, etc. </li></ul></ul>
    360. 360. Top 10 Misconceptions <ul><li>(8) There’s no evidence that patterns help anybody. </li><ul><li>Improve teaching and communication. </li></ul><li>(9) The pattern community is a clique of elites. </li><ul><li>Attendees of Pattern Languages of Programming (PLoP) conferences included analysts, designers, implementors, students, professionals, authors, even a non-computer scientist. </li></ul><li>(10) The pattern community is self-serving, even conspiratorial. </li><ul><li>Common desire of leading pattern authors is to impart expertise, best practices, and competitive advantage to others. </li></ul></ul>
    361. 361. Thank You... [email_address]