Kyle Brown An Introduction to Patterns Senior Member of Technical Staff and Languages Knowledge Systems Corp. 4001 Weston Parkway CSC591O Cary, North Carolina 27513-2303 April 7-9, 1997 919-481-4000 Raleigh, NC [email protected] http://www.ksccary.com Copyright (C) 1996, Kyle Brown, Bobby Woolf, and 1 2 Knowledge Systems Corp. All rights reserved.

Overview

Bobby Woolf Senior Member of Technical Staff O Patterns Knowledge Systems Corp. O Patterns 4001 Weston Parkway O Patterns Cary, North Carolina 27513-2303 O Architectural Patterns 919-481-4000 O Pattern Catalogs [email protected] O Pattern Languages http://www.ksccary.com

3 4

Patterns -- Why? Patterns -- Why?

!@#$ O Learning software development is hard » Lots of new concepts O Must be some way to » Hard to distinguish good communicate better ideas from bad ones » Allow us to concentrate O Languages and on the problem frameworks are very O Patterns can provide the complex answer » Too much to explain » Much of their structure is incidental to our problem

5 6 Patterns -- What? Patterns -- Parts

O Patterns are made up of four main parts O What is a pattern? » Title -- the name of the pattern » A solution to a problem in a context » Problem -- a statement of what the pattern solves » A structured way of representing design » Context -- a discussion of the constraints and information in prose and diagrams forces on the problem »A way of communicating design information from an expert to a novice » Solution -- a description of how to solve the problem » Generative: show when and how to apply solutions –This may include a list of the participants in the pattern » One of the hottest topics in OO Design O May have other sections

7 8

Patterns -- Origin (1) Patterns -- Origin (2)

O Pattern concept came from architecture » A O [Alexander77] describes » A Timeless Way of » Common architectural Building [Alexander79] motifs O Alexander used patterns » How they can come to together to form a » Express the interaction of cohesive, liveable forces in a problem environment » Arrive at an elegant solution

9

Patterns -- Doors Example (1) Patterns -- Doors Example (2)

O Corner Doors O Solution: “...in most » [196 in Alexander77] rooms, especially small O Problem: How do you ones, put the doors as near place the doors in a room? the corners of the room as “untouched by O “If the doors create a possible.” movement” pattern of movement O “If a room has two doors, G! which destroys the places N and people move through BA in a room, the room will it, keep both doors at one never allow people to be end of the room.” comfortable.” Software Patterns -- What? Software Patterns -- Why?

O and from O Abstractors and Elaborators [Beck94] O In 1987, they applied Alexander’s ideas to » Abstractors create reusable pieces designing user interfaces (frameworks) » “Nouns in Lists, Verbs in Menus” » Elaborators use pieces to » “Window per Task” build applications » Abstractors must explain O The idea was independently discovered pieces to elaborators » of AT&T [Coplien92] » Patterns are an efficient »Others explanation of intent

13 14

Software Patterns -- Why? Software Pattern -- GUIs

O Patterns support O Nouns in Lists, Verbs in Menus reusable software O Problem: »Many more elaborators than abstractors (100:1?) »Designing a GUI: What goes in lists vs. menus? » More efficient explanation, more blah blah blah efficient reuse blah » More powerful than a blah blah faster compiler or better ? blah tools

15 16

Nouns in lists... Nouns in lists… (2)

O Context: O Solution: » Principle of least astonishment » Put nouns in lists, verbs in menus » People expect to perform actions on subjects » List of actions without subjects looks incomplete edit tree » Select a subject first, then an action house copy ? cut

17 18 Patterns have exploded! Architectural Patterns

Architectural Analysis Patterns O Deal with the highest levels of software Patterns development O Often discovered in very large projects Alexander’s O A few published examples Patterns Organizational Design » Coad, Object Models: Strategies Patterns and Patterns Patterns 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 Solution: Divide the task O Problem: Building Lexical Analysis into sequential Systems to Transform processing steps and Process Streams of (filters). Syntax Analysis/Parsing Data O Steps are connected by » Different steps of the process may be data flow components Semantic Analysis represented differently (pipes) »Many intermediate data O Example: Compiler forms Code Generation

21 22

Architectural Pattern -- Four Layer Architecture (1) Four Layer Architecture (2)

O Problem: »How do you structure an application with O Solution: significant presentation » Divide classes into layers and model components? » The MVC architecture of O Forces: -80 separated »Existing structures the “model” and “view” » Code reuse components » Distribution of work » More layers are needed among team members to model all necessary abstractions »Portability to new environments and language vendors Smalltalk Application Layers Layer purposes

O View layer - provides the graphical view of an application. Handles user interaction O View layer Application layer - Mediates between different views of an application. Adapts the protocol Application layer of the View layer to the protocol of the domain model. Domain layer O Domain layer - Represents the business or Infrastructure layer “real-world” model of the application O Infrastructure layer - supports the domain layer with connections to external interfaces

Analysis Patterns Analysis Patterns

O Written by Martin Fowler O Deals with common O Patterns about Analysis business domains O Are they patterns about the Analysis process, » Accounting »Finance or patterns found in ? » Inventory O Both have been published... O Includes general purpose analysis patterns

27 28

An Analysis Pattern Account - Solution

Account Entry Transaction entries O Account balance : Quantity amount : Quantity whenCharged : TimeStamp 2 O Problem: In many fields whenBooked : TimeStamp you must keep records Constraint: Constraint: of not just the current balance = sum(entries.amount) value of a thing, but the sum (entries.amount) = 0 changes that have affected that value. Basic Double-Entry Accounting!

29 30 Design Patterns -- Gang of Four

O Gang of Four is , Richard Helm, O Design Patterns are patterns about OO Ralph Johnson and John Vlissides design O Collaborated on finding patterns in software O Discuss tradeoffs inherent in the process over a series of years O Evaluate alternative O Finally decided to write a book

31 32

A -- Strategy Design Patterns (315)

O Their book is Design Patterns: Elements of Reusable Object- O Often you have the “Choose 1 of N Oriented Software algorithms” problem. [GHJV95] O Example: Converting different file formats O 23 basic design patterns found in many large OO » GIF, JPEG, EPS, etc. systems O You could write one “FileReader” with a LOT O A pattern catalog of case statements. » Patterns are not dependent on each other

33 34

Strategy Solution Strategy Structure

O Define a family of algorithms strategy Client AbstractStrategy » Various approaches to solving a problem » Encapsulate them as objects » Make them polymorphic O Client requests problem StrategyA StrategyB be solved O Strategy directs how problem is solved

35 36 Example Strategy Strategy Benefits

strategy FileConverter AbstractReader O convertFrom:to: readFileNamed: Avoids case statements O Easily extensible » just add new Strategy subclasses O Strategy classes may be GIFReader JPGReader reusable elsewhere readFileNamed: readFileNamed:

37 38

A Design Pattern -- State (305) State Solution

O Sometimes you have an object that acts O Define a set of State differently over time. objects. O Example: A TCPConnection O Defer the » You can’t open an opened one or close a closed implementation of the one. different methods to the O You could use methods like become: or state object. changeClassToThatOf: O The client changes its state from time to time. » leads to messy, difficult code

39 40

TCP Example STD TCP Example Hierarchy

transmit state TCPConnection TCPState ActiveOpen( ) ActiveOpen( ) Close( ) Close( ) activeOpen PassiveOpen( ) PassiveOpen( ) Closed Established

state.ActiveOpen() TCPClosed passiveOpen send TCPEstablished TCPListen ActiveOpen( ) ActiveOpen( ) ActiveOpen( ) close Close( ) Close( ) Close( ) PassiveOpen( ) PassiveOpen( ) PassiveOpen( ) Listen

41 42 State Benefits Why use Design Patterns

O Proven solutions to common OO problems O Makes state transitions explicit O Confer expertise to beginners O Localizes behavior; better allocation of O Common vocabulary for designers responsibility O Documentation for existing frameworks O Eliminates the need for case statements O Once internalized, good design techniques O Since the States are objects, the State become second nature Machine can be reconfigured on the fly 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 O Often called idioms object -- not a class! O Can be found in any language (not just OO) » Don’t blindly implement all 23 as classes! O They are the way experts do things O Scout around the intents to find a close match » take advantage of language features O Page through the diagrams » exploit knowledge of language and library internals

45 46

Smalltalk Idioms C++ Idioms

O Many found in O Many found in Smalltalk Advanced C++ Best Practice Patterns Programming Styles O Written by Kent Beck and Idioms O Contains Smalltalk O Written by Jim Coplien idioms, programming O Contains a lot of C++ practice patterns, and idioms (including some many others very good Memory Mgt. ones)

47 48 An example Smalltalk Idiom Organizational Patterns

O Problem: How do you implement a Stack? O Patterns about forming, O Solution: Simulate a Stack using managing and OrderedCollection understanding organizations and their Stack Operation OrderedCollection message behavior push addLast: O Often tied to software pop removeLast: more closely than you think... top last empty isEmpty 49 50

Organizational Patterns Pattern Languages -- What?

O What is a pattern O Generative Development-Process [Coplien95] language? » 42 patterns discuss team members, team O A collection of related organization, and patterns » Pattern 14: Conway’s Law O Each pattern leads to –organization determines architecture and vice versa others » Pattern 15: Architect also implements O Combine to solve an – keep the roles synchronized entire domain of » Pattern 32: Divide and Conquer problems – cluster roles that collaborate strongly, form separate O Multiple solutions from organizations multiple paths 51 52

What a pattern language is NOT Pattern Languages -- Origin

O (again) » A Pattern Language [Alexander77] O NOT a new computer » A Timeless Way of Building [Alexander79] language! O O NOT a formal language [Beck94] per se » Promotes patterns and pattern languages for O NOT an arbitrary software collection of patterns -- » Started the PLoP (Pattern Languages of that’s called a catalog Programming) conferences » Editted and published the PLoP books [PLoP95 and PLoP96]

53 54 Pattern Language -- Self- Pattern Language -- Crossing Encapsulation Chasms [Brown96]

O Self-Encapsulation [Auer95] Representing Objects as Tables » Define Classes by Behavior, Not State » Implement Behavior with Abstract State » Identify Message Layers Representing Object » Defer Identification of State Variables Relationships Representing » Encapsulate Concrete State Foreign Key Inheritance Object » Use Reference Identifer » Define Default Values via Explicit Protocol O Explains how to develop an extensible hierarchy Representing Collections 55 56

Review (1) Review (2)

O Software Patterns O Patterns » Patterns for software development » Solutions to common problems » Architecture, design, implementation » Explain the assumptions behind the solution » Reuse of expertise » Define names and scope for common techniques O Architectural Patterns » Show when and how to apply techniques » Recurring architectural structures » Document expertise O Analysis Patterns » Recurring object models

57 58

Review (3) Review (4)

O Pattern Languages O Design Patterns » Series of closely related patterns » Recurring OO design structures and techniques » Each pattern builds on others » Commonly found in successful frameworks » Represents a series of decisions O Idioms O Pattern Catalogs » Recurring code structures » A collection of loosely related patterns » Each pattern stands on its own

59 60 Further Reading (1) Further Reading (2)

O [Beck94] Beck, Kent. “Patterns and Software O [Alexander77] Alexander, Christopher, et. al. A Development,” Dr. Dobb’s Journal, Feb. 1994, 19(2). Pattern Language: Towns, Buildings, Construction. O Oxford University Press, New York, NY, 1977, ISBN [Beck96] Beck, Kent. Smalltalk Best Practice 0-19-501919-9; http://www.oup.co.uk/. Practices. Prentice-Hall, 1996, ISBN 0-13-476904-X; http://www.prenhall.com/. O [Alexander79] Alexander, Christopher. The Timeless O Way of Building. Oxford University Press, New York, [Brown] Brown, Kyle & Whitenack, Bruce, “Crossing NY, 1979, ISBN 0-19-502402-8; Chasms: A Pattern Language for Object-RDBMS http://www.oup.co.uk/. integration”, http://www.ksccary.com/ordbjrnl.htm O O [Auer95] Auer, Ken. “Reusability Through Self- [Buschmann], Buschmann, Frank, et. al. Pattern- Oriented , A System of Patterns, Encapsulation” in [PLoP95]. John Wiley & Sons, 1996, ISBN 0-471-95869-7 61 62

Further Reading (3) Further Reading (4)

O [Coplien92] Coplien, James. Advanced C++: O [GHJV95] Gamma, Erich, Richard Helm, Ralph Programming Styles and Idioms. Addison-Wesley Johnson, and John Vlissides. Design Patterns: Publishing, Reading, MA, 1992, ISBN 0-201-54855-0; Elements of Reusable Object-Oriented Software. http://heg-school.aw.com/cseng/authors/coplien/ Addison-Wesley Publishing, Reading, MA, 1995, styles/styles.html. ISBN: 0-201-63361-2; O [Coplien95] Coplien, James. “A Generative http://www.aw.com/cp/Gamma.html. Development-Process Pattern Language” in [PloP95]. O [Johnson92] Johnson, Ralph. “Documenting O [Fowler] Fowler, Martin. Analysis Patterns: Reusable Frameworks using Patterns”, OOPSLA ‘92 Object Models, Addison-Wesley Publishing, Reading, Conference Proceedings, ACM Press, 1992. MA, 1996, ISBN 0-201-89542-0

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://heg- O [PPR] The Portland Pattern Repository, school.aw.com/cseng/authors/ http://c2.com/ppr/. coplien/patternlang/patternlang.html. O [UIUC] UIUC Patterns Home Page, http://st- O [PLoP96] Vlissides, John, James Coplien, and www.cs.uiuc.edu/patterns/. Norman Kerth, Editors. Pattern Languages of O [Woolf95] Woolf, Bobby. “A Sample Pattern Program Design 2. Addison-Wesley Publishing, Language.” The Smalltalk Report. Feb 1995, 4(5). Reading, MA, 1996, ISBN 0-201-89527-7; http://heg- school.aw.com/cseng/authors/vlissides/plop2/ plop2.html. 65 66