An Introduction to Patterns and Pattern Languages CSC591O April 7-9, 1997 Raleigh, NC Copyright (C) 1996, Kyle Brown, Bobby Woolf, and Knowledge Systems Corp. All rights reserved. 1 Kyle Brown Senior Member of Technical Staff Knowledge Systems Corp. 4001 Weston Parkway Cary, North Carolina 27513-2303 919-481-4000 kbrown@ksccary.com http://www.ksccary.com 2 Overview Bobby Woolf Senior Member of Technical Staff Knowledge Systems Corp. 4001 Weston Parkway Cary, North Carolina 27513-2303 919-481-4000 bwoolf@ksccary.com http://www.ksccary.com 3 O Patterns O Software Patterns O Design Patterns O Architectural Patterns O Pattern Catalogs O Pattern Languages 4 Patterns -- Why? Patterns -- Why?!@#$ O Learning software development is hard» Lots of new concepts» Hard to distinguish good ideas from bad ones O Languages and frameworks are very complex» Too much to explain» Much of their structure is incidental to our problem O Must be some way to communicate better» Allow us to concentrate on the problem O Patterns can provide the answer 5 6
Patterns -- What? Patterns -- Parts O What is a pattern?» A solution to a problem in a context» A structured way of representing design information in prose and diagrams»a way of communicating design information from an expert to a novice» Generative: show when and how to apply solutions» One of the hottest topics in OO Design O Patterns are made up of four main parts» Title -- the name of the pattern» Problem -- a statement of wha the pattern solves» Context -- a discussion of the constraints and forces on the problem» Solution -- a description of how to solve the problem This may include a list of the participants in the pattern O May have other sections 7 8 Patterns -- Origin (1) Patterns -- Origin (2) O Pattern concept came from architecture» A Pattern Language [Alexander77]» A Timeless Way of Building [Alexander79] O Alexander used patterns to» Express the interaction of forces in a problem» Arrive at an elegant solution O A Pattern Language describes» Common architectural motifs» How they can come together to form a cohesive, liveable environment 9 Patterns -- Doors Example (1) Patterns -- Doors Example (2) O Corner Doors» [196 in Alexander77] O Problem: How do you place the doors in a room? O If the doors create a pattern of movement which destroys the places in a room, the room will never allow people to be comfortable. BANG! O Solution:...in most rooms, especially small ones, put the doors as near the corners of the room as possible. O If a room has two doors, and people move through it, keep both doors at one end of the room. untouched by movement
Software Patterns -- What? Software Patterns -- Why? O Ward Cunningham and Kent Beck from Tektronix O In 1987, they applied Alexander s ideas to designing user interfaces» Nouns in Lists, Verbs in Menus» Window per Task O The idea was independently discovered» Jim Coplien of AT&T [Coplien92]»Others O Abstractors and Elaborators [Beck94]» Abstractors create reusable pieces (frameworks)» Elaborators use pieces to build applications» Abstractors must explain pieces to elaborators» Patterns are an efficient explanation of intent 13 14 Software Patterns -- Why? Software Pattern -- GUIs O Patterns support reusable software» Many more elaborators than abstractors (100:1?)» More efficient explanation, more efficient reuse» More powerful than a faster compiler or better tools O Nouns in Lists, Verbs in Menus O Problem:»Designing a GUI: What goes in lists vs. menus? blah blah? blah blah blah blah blah 15 16 Nouns in lists... Nouns in lists (2) O Context:» Principle of least astonishment» People expect to perform actions on subjects» List of actions without subjects looks incomplete» Select a subject first, then an action O Solution:» Put nouns in lists, verbs in menus tree house? edit copy cut 17 18
Patterns have exploded! Architectural Patterns Architectural Patterns Organizational Patterns Alexander s Patterns Analysis Patterns Design Patterns O Deal with the highest levels of software development O Often discovered in very large projects O A few published examples» Coad, Object Models: Strategies Patterns and Applications» Buschmann, Pattern Oriented Software Architectures: A System of Patterns Language-Specific Patterns 19 20 Architectural Pattern - Pipes and Filters Pipes and Filters (2) O From [Buschmann96] O Problem: Building Systems to Transform and Process Streams of Data» Different steps of the process may be represented differently» Many intermediate data forms O Solution: Divide the task into sequential processing steps (filters). O Steps are connected by data flow components (pipes) O Example: Compiler Lexical Analysis Syntax Analysis/Parsing Semantic Analysis Code Generation 21 22 Architectural Pattern -- Four Layer Architecture (1) Four Layer Architecture (2) O Problem:» How do you structure an application with significant presentation and model components? O Forces:» Existing structures» Code reuse» Distribution of work among team members» Portability to new environments and language vendors O Solution:» Divide classes into layers» The MVC architecture of Smalltalk-80 separated the model and view components» More layers are needed to model all necessary abstractions
Smalltalk Application Layers View layer Application layer Domain layer Infrastructure layer Layer purposes O View layer - provides the graphical view of an application. Handles user interaction O Application layer - Mediates between different views of an application. Adapts the protocol of the View layer to the protocol of the domain model. O Domain layer - Represents the business or real-world model of the application O Infrastructure layer - supports the domain layer with connections to external interfaces Analysis Patterns Analysis Patterns O Patterns about Analysis O Are they patterns about the Analysis process, or patterns found in systems analysis? O Both have been published... O Written by Martin Fowler O Deals with common business domains» Accounting» Finance» Inventory O Includes general purpose analysis patterns 27 28 An Analysis Pattern Account - Solution O Account O Problem: In many fields you must keep records of not just the current value of a thing, but the changes that have affected that value. Account Entry entries balance : Quantity amount : Quantity whencharged : TimeStamp 2 whenbooked : TimeStamp Constraint: balance = sum (entries.amount) Transaction Constraint: sum(entries.amount) = 0 Basic Double-Entry Accounting! 29 30
Design Patterns Design Patterns -- Gang of Four O Design Patterns are patterns about OO design O Discuss tradeoffs inherent in the process O Evaluate alternative designs O Gang of Four is Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides O Collaborated on finding patterns in software over a series of years O Finally decided to write a book 31 32 Design Patterns A Design Pattern -- Strategy (315) O Their book is Design Patterns: Elements of Reusable Object- Oriented Software [GHJV95] O 23 basic design patterns found in many large OO systems O A pattern catalog» Patterns are not dependent on each other O Often you have the Choose 1 of N algorithms problem. O Example: Converting different file formats» GIF, JPEG, EPS, etc. O You could write one FileReader with a LOT of case statements. 33 34 Strategy Solution Strategy Structure O Define a family of algorithms» Various approaches to solving a problem» Encapsulate them as objects» Make them polymorphic O Client requests problem be solved O Strategy directs how problem is solved Client strategy AbstractStrategy StrategyA StrategyB 35 36
Example Strategy Strategy Benefits FileConverter convertfrom:to: strategy AbstractReader readfilenamed: GIFReader JPGReader readfilenamed: readfilenamed: O Avoids case statements O Easily extensible» just add new Strategy subclasses O Strategy classes may be reusable elsewhere 37 38 A Design Pattern -- State (305) State Solution O Sometimes you have an object that acts differently over time. O Example: A TCPConnection» You can t open an opened one or close a closed one. O You could use methods like become: or changeclasstothatof:» leads to messy, difficult code O Define a set of State objects. O Defer the implementation of the different methods to the state object. O The client changes its state from time to time. 39 40 TCP Example STD TCP Example Hierarchy Closed activeopen transmit Established TCPConnection ActiveOpen( ) Close( ) PassiveOpen( ) state TCPState ActiveOpen( ) Close( ) PassiveOpen( ) passiveopen send close state.activeopen() TCPEstablished ActiveOpen( ) Close( ) PassiveOpen( ) TCPListen ActiveOpen( ) Close( ) PassiveOpen( ) TCPClosed ActiveOpen( ) Close( ) PassiveOpen( ) Listen 41 42
State Benefits Why use Design Patterns O Makes state transitions explicit O Localizes behavior; better allocation of responsibility O Eliminates the need for case statements O Since the States are objects, the State Machine can be reconfigured on the fly O Proven solutions to common OO problems O Confer expertise to beginners O Common vocabulary for designers O Documentation for existing frameworks O Once internalized, good design techniques become second nature O Often combined to create more sophisticated designs 43 44 How to use Design Patterns Languages-Specific Patterns O Usually the pattern describes a role for an object -- not a class!» Don t blindly implement all 23 as classes! O Scout around the intents to find a close match O Page through the diagrams O Often called idioms O Can be found in any language (not just OO) O They are the way experts do things» take advantage of language features» exploit knowledge of language and library internals 45 46 Smalltalk Idioms C++ Idioms O Many found in Smalltalk Best Practice Patterns O Written by Kent Beck O Contains Smalltalk idioms, programming practice patterns, and many others O Many found in Advanced C++ Programming Styles and Idioms O Written by Jim Coplien O Contains a lot of C++ idioms (including some very good Memory Mgt. ones) 47 48
An example Smalltalk Idiom Organizational Patterns O Problem: How do you implement a Stack? O Solution: Simulate a Stack using OrderedCollection Stack Operation push pop top empty OrderedCollection message addlast: removelast: last isempty 49 O Patterns about forming, managing and understanding organizations and their behavior O Often tied to software more closely than you think... 50 Organizational Patterns Pattern Languages -- What? O Generative Development-Process [Coplien95]» 42 patterns discuss team members, team organization, and project management» Pattern 14: Conway s Law organization determines architecture and vice versa» Pattern 15: Architect also implements keep the roles synchronized» Pattern 32: Divide and Conquer cluster roles that collaborate strongly, form separate organizations 51 O What is a pattern language? O A collection of related patterns O Each pattern leads to others O Combine to solve an entire domain of problems O Multiple solutions from multiple paths 52 What a pattern language is NOT Pattern Languages -- Origin O NOT a new computer language! O NOT a formal language per se O NOT an arbitrary collection of patterns -- that s called a catalog 53 O Christopher Alexander (again)» A Pattern Language [Alexander77]» A Timeless Way of Building [Alexander79] O The Hillside Group [Beck94]» Promotes patterns and pattern languages for software» Started the PLoP (Pattern Languages of Programming) conferences» Editted and published the PLoP books [PLoP95 and PLoP96] 54
Pattern Language -- Self- Encapsulation Pattern Language -- Crossing Chasms [Brown96] O Self-Encapsulation [Auer95]» Define Classes by Behavior, Not State» Implement Behavior with Abstract State» Identify Message Layers» Defer Identification of State Variables» Encapsulate Concrete State» Use Lazy Initialization» Define Default Values via Explicit Protocol O Explains how to develop an extensible hierarchy 55 Representing Objects as Tables Object Identifer Representing Object Relationships Foreign Key Reference Representing Inheritance Representing Collections 56 Review (1) Review (2) O Patterns» Solutions to common problems» Explain the assumptions behind the solution» Define names and scope for common techniques» Show when and how to apply techniques» Document expertise O Software Patterns» Patterns for software development» Architecture, design, implementation» Reuse of expertise O Architectural Patterns» Recurring architectural structures O Analysis Patterns» Recurring object models 57 58 Review (3) Review (4) O Design Patterns» Recurring OO design structures and techniques» Commonly found in successful frameworks O Idioms» Recurring code structures O Pattern Languages» Series of closely related patterns» Each pattern builds on others» Represents a series of decisions O Pattern Catalogs» A collection of loosely related patterns» Each pattern stands on its own 59 60
Further Reading (1) Further Reading (2) O [Alexander77] Alexander, Christopher, et. al. A Pattern Language: Towns, Buildings, Construction. Oxford University Press, New York, NY, 1977, ISBN 0-19-501919-9; http://www.oup.co.uk/. O [Alexander79] Alexander, Christopher. The Timeless Way of Building. Oxford University Press, New York, NY, 1979, ISBN 0-19-502402-8; http://www.oup.co.uk/. O [Auer95] Auer, Ken. Reusability Through Self- Encapsulation in [PLoP95]. O [Beck94] Beck, Kent. Patterns and Software Development, Dr. Dobb s Journal, Feb. 1994, 19(2). O [Beck96] Beck, Kent. Smalltalk Best Practice Practices. Prentice-Hall, 1996, ISBN 0-13-476904-X; http://www.prenhall.com/. O [Brown] Brown, Kyle & Whitenack, Bruce, Crossing Chasms: A Pattern Language for Object-RDBMS integration, http://www.ksccary.com/ordbjrnl.htm O [Buschmann], Buschmann, Frank, et. al. Pattern- Oriented Software Architecture, A System of Patterns, John Wiley & Sons, 1996, ISBN 0-471-95869-7 61 62 Further Reading (3) Further Reading (4) O [Coplien92] Coplien, James. Advanced C++: Programming Styles and Idioms. Addison-Wesley Publishing, Reading, MA, 1992, ISBN 0-201-54855-0; http://heg-school.aw.com/cseng/authors/coplien/ styles/styles.html. O [Coplien95] Coplien, James. A Generative Development-Process Pattern Language in [PloP95]. O [Fowler] Fowler, Martin. Analysis Patterns: Reusable Object Models, Addison-Wesley Publishing, Reading, MA, 1996, ISBN 0-201-89542-0 O [GHJV95] Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Publishing, Reading, MA, 1995, ISBN: 0-201-63361-2; http://www.aw.com/cp/gamma.html. O [Johnson92] Johnson, Ralph. Documenting Frameworks using Patterns, OOPSLA 92 Conference Proceedings, ACM Press, 1992. 63 64 Further Reading (5) Further Reading (6) O [PLoP95] Coplien, James, and Schmidt, Douglas, Editors. Pattern Languages of Program Design. Addison-Wesley Publishing, Reading, MA, 1995, ISBN 0-201-60734-4; http://hegschool.aw.com/cseng/authors/ coplien/patternlang/patternlang.html. O [PLoP96] Vlissides, John, James Coplien, and Norman Kerth, Editors. Pattern Languages of Program Design 2. Addison-Wesley Publishing, Reading, MA, 1996, ISBN 0-201-89527-7; http://hegschool.aw.com/cseng/authors/vlissides/plop2/ plop2.html. 65 O [PPR] The Portland Pattern Repository, http://c2.com/ppr/. O [UIUC] UIUC Patterns Home Page, http://stwww.cs.uiuc.edu/patterns/. O [Woolf95] Woolf, Bobby. A Sample Pattern Language. The Smalltalk Report. Feb 1995, 4(5). 66