Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Patterns and Frameworks

CS 342: Object-Oriented Software Development Lab  Motivation for Patterns and Frameworks

Introduction to Patterns and Frameworks  What is a Pattern? A Framework?

 Pattern Categories Dr. David L. Levine and Douglas C. Schmidt

Department of Computer Science  Pattern Examples Washington University, St. Louis

f levine,schmidtg @cs.wustl.edu

http://classes.cec.wustl.edu/ cs342/

Department of Computer Science 1 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Motivation for Patterns and Frameworks Overview of Patterns and Frameworks

 Patterns support reuse of software architecture and design  Developing software is hard – Patterns capture the static and dynamic structures and  Developing reusable software is even harder collaborations of successful solutions to problems that arise when

 Proven solutions include patterns and frameworks building applications in a particular domain

 Frameworks support reuse of detailed design and code – A framework is an integrated set of components that collaborate to provide a reusable architecture for a family of related applications.

 Together, and frameworks help to improve software quality and reduce development time – e.g., reuse, extensibility, modularity, performance

Department of Computer Science 2 Washington University, St. Louis Department of Computer Science 3 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Patterns of Learning Becoming a Chess Master

learning  First learn rules and physical requirements

 Successful solutions to many areas of human endeavor are deeply rooted in patterns – e.g., names of pieces, legal movements, chess board geometry and orientation, etc. – In fact, an important goal of education is transmitting patterns of

from generation to generation  Then learn principles

 Below, we’ll explore how patterns are used to learn chess – e.g., relative value of certain pieces, strategic value of center squares, power of a threat, etc.

 Learning to develop good software is similar to learning to play good

chess  However, to become a master of chess, one must study the games of other masters – Though the consequences of failure are often far less dramatic! – These games contain patterns that must be understood, memorized, and applied repeatedly

 There are hundreds of these patterns

Department of Computer Science 4 Washington University, St. Louis Department of Computer Science 5 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Becoming a Software Design Master Design Patterns

 First learn the rules  Design patterns represent solutions to problems that arise when developing software within a particular context – e.g., the algorithms, data structures and languages of software – i.e., “Patterns == problem/solution pairs in a context”

 Then learn the principles

 Patterns capture the static and dynamic structure and collaboration – e.g., structured programming, modular programming, object among key participants in software designs oriented programming, generic programming, etc. – They are particularly useful for articulating how and why to

 However, to truly master software design, one must study the resolve non-functional forces designs of other masters

 Patterns facilitate reuse of successful software architectures and – These designs contain patterns must be understood, memorized, designs and applied repeatedly

 There are hundreds of these patterns

Department of Computer Science 6 Washington University, St. Louis Department of Computer Science 7 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Example: Stock Quote Service SUBJECT REAL -TIME

MODEL MARKET  Intent DATA FEED – Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

 Key forces 1. There may be many observers STOCK 2. Each observer may react differently to the same notification QUOTES 3. The subject should be as decoupled as possible from the observers to allow observers to change independently of the OBSERVERS subject

Department of Computer Science 8 Washington University, St. Louis Department of Computer Science 9 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Structure of the Observer Pattern Graphical Notation 1N foreach o in observers loop o.update() Observer end loop update() PROCESS Subject observers notify() APPLICATION attach(observer) INDEPENDENT

detach(observer) APPLICATION Concrete DEPENDENT OBJECT TEMPLATE Observer : CLASS CLASS Concrete update() Subject subject subject->get_state() get_state() subject_state_ return subject_state_ INHERITS CONTAINMENT

Department of Computer Science 10 Washington University, St. Louis Department of Computer Science 11 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Collaboration in the Observer Pattern Design Pattern Descriptions Concrete Concrete Concrete

Subject Observer 1 Observer 2  Main parts set_state() 1. Name and intent 2. Problem and context 3. Force(s) addressed notify() update() 4. Abstract description of structure and collaborations in solution 5. Positive and negative consequence(s) of use get_state() 6. Implementation guidelines and sample code 7. Known uses and related patterns

update()  Pattern descriptions are often independent of programming language or implementation details get_state() – Contrast with frameworks . . .

Department of Computer Science 12 Washington University, St. Louis Department of Computer Science 13 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Frameworks Class Libraries vs. Frameworks vs. Patterns

NETWORKING  1. Frameworks are semi-complete applications APPLICATION Definition SPECIFIC INVOKES LOGIC MATH ADT S – Class libraries  Complete applications are developed by inheriting from, and

EVENT USER  Self-contained, instantiating parameterized framework components DATA LOOP INTERFACE BASE “pluggable” ADTs 2. Frameworks provide domain-specific functionality – Frameworks (A) CLASS LIBRARY ARCHITECTURE  Reusable,

 e.g., business applications, telecommunication applications, “semi-complete” window systems, databases, distributed applications, OS kernels NETWORKING USER MATH INTERFACE applications APPLICATION 3. Frameworks exhibit at run-time CALL – Patterns INVOKES SPECIFIC BACKS LOGIC EVENT  Problem, solution,

 i.e., the framework determines which objects and methods to LOOP ADT S context invoke in response to events DATABASE (B) FRAMEWORK ARCHITECTURE

Department of Computer Science 14 Washington University, St. Louis Department of Computer Science 15 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Component Integration in Frameworks Comparing Pattern and Frameworks

 Framework components are loosely coupled via “callbacks”  Patterns and frameworks are highly synergistic concepts, with neither subordinate to the other

 Callbacks allow independently developed software components to

be connected together  Patterns have been characterized as more abstract descriptions of frameworks, which are then implemented in a particular language

 Callbacks provide a connection-point where generic framework

objects can communicate with application objects  Sophisticated frameworks typically embody dozens of patterns

– The framework provides the common template methods and the  Likewise, patterns have been used to document frameworks application provides the variant hook methods

Department of Computer Science 16 Washington University, St. Louis Department of Computer Science 17 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Design Pattern Space Creational Patterns

 Factory Method

 Creational patterns – Method in a derived class creates associates – Deal with initializing and configuring classes and objects

 Abstract Factory

 Structural patterns – Factory for building related objects – Deal with decoupling interface and implementation of classes and

 Builder objects – Factory for building complex objects incrementally

 Behavioral patterns

 Prototype – Deal with dynamic interactions among societies of classes and objects – Factory for cloning new instances from a prototype

 Singleton – Factory for a singular (sole) instance

Department of Computer Science 18 Washington University, St. Louis Department of Computer Science 19 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Structural Patterns Structual Patterns (cont’d)

 Adapter  Facade – Translator adapts a server interface for a client – Facade simplifies the interface for a subsystem

 Bridge  Flyweight – Abstraction for binding one of many implementations – Many fine-grained objects shared efficiently

 Composite  Proxy – Structure for building recursive aggregations – One object approximates another

 Decorator – Decorator extends an object transparently

Department of Computer Science 20 Washington University, St. Louis Department of Computer Science 21 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Behavioral Patterns Behavioral Patterns (cont’d)

 Chain of Responsibility  Mediator – Request delegated to the responsible service provider – Mediator coordinates interactions between its associates

 Command  Memento – Request as first-class object – Snapshot captures and restores object states privately

 Interpreter  Observer – Language interpreter for a small grammar – Dependents update automatically when a subject changes

 Iterator  State – Aggregate elements are accessed sequentially – Object whose behavior depends on its state

Department of Computer Science 22 Washington University, St. Louis Department of Computer Science 23 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Behavioral Patterns (cont’d) When to Use Patterns

1. Solutions to problems that recur with variations  Strategy

– Abstraction for selecting one of many algorithms  No need for reuse if the problem only arises in one context 2. Solutions that require several steps  Template Method

– Algorithm with some steps supplied by a derived class  Not all problems need all steps

 Patterns can be overkill if solution is simple linear set of

 Visitor instructions – Operations applied to elements of an heterogeneous object 3. Solutions where the solver is more interested in the existence of the structure solution than its complete derivation

 Patterns leave out too much to be useful to someone who really wants to understand – They can be a temporary bridge, however . . .

Department of Computer Science 24 Washington University, St. Louis Department of Computer Science 25 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction What Makes it a Pattern? Case Study: A Reusable OO Communication Software A pattern must: Framework

 solve a problem ,  teach

 Developing portable, reusable, and efficient communication software – i.e.,itmustbeuseful! – It must provide sufficient is hard understanding to tailor the

  have a context , OS platforms are often fundamentally incompatible solution. – It must describe where the – e.g., different concurrency and I/O models

 haveaname. solution can be used.

 Thus, it may be impractical to directly reuse: – It must be referred to

 recur, consistently. – Algorithms – It must be relevant in other – Detailed designs situations. – Interfaces – Implementations

Department of Computer Science 26 Washington University, St. Louis Department of Computer Science 27 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction System Overview Problem: Cross-platform Reuse

SUPER - SUPER - SUPER - VISOR VISOR VISOR SUPER - VISOR  Original OO framework was developed for UNIX and later ported to Windows NT 3.51 in 1993 NETWORK

 UNIX and Windows NT have fundamentally different I/O models

MD110 ERICSSON – i.e., synchronous vs. asynchronous

MD110 ERICSSON SWITCH SUPERVISOR  Thus, direct reuse of original framework was infeasible . . . HANDLERS HANDLERS EVENT : Reactor SERVER – Later solved by ACE and Windows NT 4.0 CALL CENTER MANAGER TELECOM SWITCHES

OO framework for call center management developed for Ericsson

www.cs.wustl.edu/ schmidt/ECOOP-95.ps.gz

Department of Computer Science 28 Washington University, St. Louis Department of Computer Science 29 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Solution: Reuse Design Patterns Example Pattern: Reactor

 Intent

 Design patterns support reuse of software architecture – Decouples synchronous event demultiplexing and event handler initiation dispatching from service(s) performed in response to  Patterns embody successful solutions to problems that arise when developing software in a particular context events.

 This pattern solves several problems for single-threaded

 Design patterns greatly reduced project risk at Ericsson by leveraging proven design expertise communication software: 1. How to demultiplex multiple types of events from multiple sources of events synchronously and efficiently within a single thread of control. 2. How to extend application behavior without requiring changes to the event dispatching framework.

 A pattern description captures the static and dynamic structure and collaboration among key participants in a micro-architecture.

Department of Computer Science 30 Washington University, St. Louis Department of Computer Science 31 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Structure and Participants in the Collaborations callback : Initiation Dispatcher select (handles); main Concrete : Initiation handle_events() foreach h in handles loop programEvent_HandlerDispatcher table[h].handle_event(type) register_handler(h) end loop remove_handler(h) handlers INITIALIZE Event Handler register_handler(callback)open() 1 N REGISTER HANDLER uses Handle owns handle_event(type) get_handle() MODE MODE handle_events() get_handle() EXTRACT HANDLE notifies INITIALIZATION INITIALIZATION START EVENT LOOP

Synchronous Event Concrete FOREACH EVENT DO select() Demultiplexer Event handle_event() select() Handler EVENT OCCURS MODE MODE EVENT EVENT REMOVE HANDLER handle_close() HANDLING HANDLING

www.cs.wustl.edu/ schmidt/Reactor.ps.gz Dynamic interaction among participants in the Reactor pattern

Department of Computer Science 32 Washington University, St. Louis Department of Computer Science 33 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Use of ACE’s Reactor Pattern Implementation Use of ACE’s Reactor Pattern Implementation (cont’d) #include "ace/Reactor.h" int main (int, char *[]) class My_Event_Handler : public ACE_Event_Handler { { public: ACE_Reactor reactor; virtual int handle_input (ACE_HANDLE fd = My_Event_Handler eh; ACE_INVALID_HANDLE) { cout << "input on fd " << fd << endl; return 0; reactor.register_handler (&eh, } ACE_Event_Handler::READ_MASK); reactor.register_handler (SIGUSR2, &eh); virtual int handle_signal (int signum, siginfo_t * = 0, while (1) ucontext_t * = 0) { reactor.handle_events (); cout << "signal " << signum << endl; return 0; } return 0; }; }

Department of Computer Science 34 Washington University, St. Louis Department of Computer Science 35 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Differences Between UNIX and Windows NT Lessons Learned from Case Study

 Reactive vs. Proactive I/O  Real-world constraints of OS platforms can preclude direct reuse of – Reactive I/O is synchronous communication software – Proactive I/O is asynchronous – e.g., must often use non-portable features for performance

 Requires additional interfaces to “arm” the I/O mechanism

– See  Reuse of design patterns may be the only viable means to leverage previous development expertise  www.cs.wustl.edu/  schmidt/proactor.ps.gz

 Design patterns are useful, but are no panacea  Other differences include – Resource limitations – Managing expectations is crucial . . .

 e.g., Windows NT limits HANDLEs per-thread to 64 – Demultiplexing fairness

 e.g., WaitForMultipleObjects always returns the lowest active HANDLE

Department of Computer Science 36 Washington University, St. Louis Department of Computer Science 37 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Key Principles Planning for Change

 Successful patterns and frameworks can be boiled down to a few  Often, aspects of a design “seem” constant until they are examined key principles: in the light of the dependency structure of an application 1. Separate interface from implementation – At this point, it becomes necessary to refactor the framework or 2. Determine what is common and what is variable with an interface pattern to account for the variation and an implementation

 Frameworks often represent the distinction between commonality – Common == stable and variability via template methods and hook methods, respectively 3. Allow substitution of variable implementations via a common interface

 Dividing commonality from variability should be goal-oriented rather than exhaustive

Department of Computer Science 38 Washington University, St. Louis Department of Computer Science 39 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction The Open/Closed Principle The Open/Closed Principle (cont’d)

 Determining common vs. variable components is important  Components should be: – Insufficient variation makes it hard for users to customize – open for extension framework components – closed for modification – Conversely, insufficient commonality makes it hard for users to

 Impacts comprehend and depend upon the framework’s behavior – Abstraction is good

 In general, dependency should always be in the direction of stability – Inheritance and polymorphism are good – i.e., a software component should not depend on any component – Public data members and global data are bad that is less stable than itself – Run-time type identification can be bad

 The “Open/Closed” principle – This principle allows the most stable component to be extensible

Department of Computer Science 40 Washington University, St. Louis Department of Computer Science 41 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Violation of Open/Closed Principle Application of Open/Closed Principle struct Shape { /* . . . */ }; class Shape { class Square : public Shape { /*...*/}; public: class Circle : public Shape { /*...*/}; virtual void draw () const = 0; void draw_square (const Square &); }; void draw_circle (const Circle &); void draw_all (const Shape &shape) { void draw_shape (const Shape &shape) { shape.draw (); switch (shape.shapeType) { } case SQUARE: draw_square ((const Square &) shape); break; case CIRCLE: draw_circle ((const Circle &) shape); break; // etc.

Department of Computer Science 42 Washington University, St. Louis Department of Computer Science 43 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Benefits of Design Patterns Drawbacks to Design Patterns

 Design patterns enable large-scale reuse of software architectures.  Patterns do not lead to direct code reuse.

– They also help document systems to enhance understanding.  Patterns are deceptively simple.

 Patterns explicitly capture expert knowledge and design tradeoffs,  Teams may suffer from pattern overload. and make this expertise more widely available.

 Patterns are validated by experience and discussion rather than by

 Patterns help improve developer communication. automated testing.

– Pattern names form a vocabulary  Integrating patterns into a software development process is a human-intensive activity.

 Patterns help ease the transition to object-oriented technology.

Department of Computer Science 44 Washington University, St. Louis Department of Computer Science 45 Washington University, St. Louis

Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Suggestions for Using Patterns Effectively Lessons Learned using OO Frameworks

 Do not recast everything as a pattern.  Benefits of frameworks – Instead, develop strategic domain patterns and reuse existing – Enable direct reuse of code (cf patterns) tactical patterns. – Facilitate larger amounts of reuse than stand-alone functions or individual classes

 Institutionalize rewards for developing patterns.

 Drawbacks of frameworks

 Directly involve pattern authors with application developers and domain experts. – High initial learning curve

 Many classes, many levels of abstraction

 Clearly document when patterns apply and do not apply. – The flow of control for reactive dispatching is non-intuitive

 Manage expectations carefully. – Verification and validation of generic components is hard

Department of Computer Science 46 Washington University, St. Louis Department of Computer Science 47 Washington University, St. Louis Dr. David L. Levine CS 342: Patterns and Frameworks Introduction Summary

 Mature engineering disciplines have handbooks that describe successful solutions to known problems – e.g., automobile designers don’t design cars using the laws of physics, they adapt adequate solutions from the handbook known to work well enough – The extra few percent of performance available by starting from scratch typically isn’t worth the cost

 Patterns can form the basis for the handbook of software engineering – If software is to become an engineering discipline, successful practices must be systematically documented and widely disseminated

Department of Computer Science 48 Washington University, St. Louis