Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns Software Engineering ITCS 3155 Fall 2008 Dr. Jamie Payton Department of Computer Science University of North Carolina at Charlotte Dec. 2, 2008 1
Announcements Deliverable 3 Extensions: due Dec. 2 at 11:59 pm (tonight) Assessments Extensions: due Dec. 3 at 11:59 pm Use new links Sent by email Posted on website Final exam Dec. 16 at 11:30 am Exam review In class on Dec. 9 Come to class prepared with questions Extra credit Attend ACM Distinguished Speaker talk Friday, Dec. 5 at 3:00 pm Woodward 106 Sign in with me to get extra credit 2
Lecture Overview Resources Chapter 15 Architectural Styles Chapter 16 Mid-Level Object-Oriented Design Patterns Chapter 17 Broker Design Patterns Chapter 18 Generator Design Patterns Chapter 19 Reactor Design Patterns GoF Book Design Patterns: Elements of Reusable Object-Oriented Software 3
Software Design Patterns A pattern is a way of reusing abstract knowledge about design a description of the problem the essence of its solution Patterns allow programmers to share knowledge about design Provide a shared design vocabulary 4
History of Design Patterns Architect Christopher Alexander A Pattern Language (1977) A Timeless Way of Building (1979) Example architectural pattern Pools of light Uniform lighting makes people feel disconnected and disoriented Create pools of light, will result in pleasant gathering places 5
History of Design Patterns in Software Engineering Community Gang of four (GoF) Gamma, Helm, Johnson, Vlissides Design Patterns: Elements of Reusable Object-Oriented Software (1995) Pattern-oriented Software Architecture (POSA) Buschmann, Meunier, Rohnert, Sommerlad, Stal Many more Conferences, symposia, other books 6
Applying Patterns in Software Design Reusable design knowledge can be captured at different levels of abstraction Architectural styles or patterns Capture design of entire systems and sub-systems Design patterns Involve several interacting classes or operations Data structures & algorithms Low-level, detailed design patterns Idioms Ways of doing things that are specific to a programming language 7
Architectural Styles An architectural style describes the kinds of architectural components and their interactions In other words, a pattern of decomposition of major software parts and their relationships, responsibilities, interactions, etc DeSCRIPTR concepts Widely used architectural styles Layered architecture Pipe and filter Shared data Event driven Model View Controller (MVC) 8
Example: Information System for Political Elections A B C D X 15 35 35 15 Y 10 40 30 20 Z 10 40 30 20 Relative Percentages A B C D D C A B Change notification Requests, modifications A=10% B=40% C=30% D=20% Application data 9
Architectural Style Example: Model-View-Controller (MVC) Applicability Interactive applications with a flexible human-computer interface Problem context The display presented to the user frequently changes over time in response to input or computation Different users have different needs for how they want to view the program s information Want to reflect data changes to all users in the way that they want to view them Want to make it easy to make changes to the user interface 10
Model-View-Controller (MVC) Solution: separate the data being manipulated from the manipulation logic and the details of display Three components: Model A problem-domain component with data and operations Independent of the user interface View A data display component Controller A component that receives and acts on user input 11
MVC Participants and Responsibilities View Each view is associated with a controller Each view is associated with the model User interacts with system only through a view s controller Defines an update procedure that is called when model changes Controller Translates user input into service requests Input is usually mouse click or keyboard input events Makes service requests on model or view May need to define update procedure 12
MVC Participants and Responsibilities Model If model is updated, model notifies all interested parties (registered views and possibly controllers) of change Views will retrieve new data from model and update displayed information 13
MVC Solution: Static Structure 14
MVC Solution: Behavior 15
Consequences: MVC Advantages Views and controllers can be easily be added, removed, or changed No need to change the domain-specific data model Views can be added or changed during execution User interface components can be changed, even at runtime 16
Consequences: MVC Disadvantages Views and controller are often hard to separate Frequent updates may slow data display and degrade user interface performance The MVC style makes user interface components (views, controllers) highly dependent on model components 17
Mid-level Design Patterns A mid-level design pattern model collaborations between modules (typically classes) Referred to simply as design patterns Main focus of research in software design patterns 18
Design Pattern Elements Name A meaningful pattern identifier Problem description (Applicability) Solution description Not a concrete design but a template for a design solution that can be instantiated in different ways Consequences The results and trade-offs of applying the pattern 19
Purpose of Patterns Behavioral Describe how classes or objects interact and distribute responsibility Observer (last time) Mediator Structural Creational Describe how classes or objects should be composed Façade Adapter Proxy Concern the process of object creation Factory method Abstract Factory 20
Scope of Patterns Scope Another dimension for classifying patterns Class patterns Relationships between classes and subclasses Established through inheritance Fixed at compile-time Object patterns Relationships between objects Changeable at run-time (most patterns) 21
Purpose and Scope Behavioral Class Use inheritance to describe algorithms and flow of control Object Describe how a group of objects cooperate to perform a task Structural Class Use inheritance to compose classes Object Describe how to compose objects Creational Class Defer some part of object creation to a subclass Object Defer some part of object creation to another object 22
Scope Purpose Creational Structural Behavioral Class Factory Method Adapter (class) Interpreter Template Method Object Abstract Factory Builder Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor 23
Textbook Classification Broker patterns a client needs a service from a supplier a broker mediates interaction between client and supplier Generator patterns a client needs a new instance of a product a generator class supplies the instance Reactor patterns a client needs to respond to an event in a target client delegates this responsibility to a reactor 24
Category Analogies Brokers stock brokers who mediate interactions between an investor (client) and the stock market (supplier) Generators interior designers who obtain material from manufacturers (products) on behalf of their clients Reactors lawn service companies that respond to conditions in a lawn (target) on behalf of a homeowner (client). 25
GoF Taxonomy of Design Patterns Behavioral Observer (reactor) Mediator (broker) Structural Adapter (broker) Façade (broker) Proxy (broker) Creational Singleton (generator) Abstract Factory (generator) Categories by GoF, textbook s classification in parentheses 26
Patterns by Example: Multiple Displays Enabled by Observer A B C D X 15 35 35 15 Y 10 40 30 20 Z 10 40 30 20 Relative Percentages A B C D D C A B Change notification Requests, modifications A=10% B=40% C=30% D=20% Application data 27
Behavioral Pattern Example: The Observer Pattern Name Observer Description Reduces coupling between interacting classes Problem description Used when one or more observers must track changes to an object Solution description Use a change-propagation mechanism between info provider (subject) and the components that use it to display (observers) The register and notify approach!!! 28
The Observer Pattern Name Observer a.k.a. publish-subscribe Description/Applicability General: When change in object state requires consistent reflection of change in other objects Want dependent objects to be decoupled from one another Specific: Separates the display of object state from the object itself Problem description Used when multiple displays of state are needed need changes to state to be reflected consistently across all displays 29
The Observer Pattern Solution description Use a change-propagation mechanism between info provider (subject) and the components that use it to display (observers) Subject Stores state of interest Provides ability for Observers to attach/detach Calls Observer s update interface Observer Provides an update interface Attaches and detaches itself from Subject 30
The Observer Pattern Subject attach (Observer) detach (Observer) notify () Concrete Subject subjectstate setstate() getstate() For all x in observers{ x.update(); } Observer update() Concrete Observer observerstate observerstate= subject getstate(); 31
Observer Pattern Consequences Can add/remove observers at any time without modifying subject Can reuse subjects without reusing observers (and vice-versa) Unexpected updates to subject can cause a cascade of unnecessary update operations on observer 32
An Aside: Observer and MVC People often confuse the Observer design pattern with the MVC architectural style MVC describes an architecture: Model Manages data Executes business processing operations View Displays information and supports user interaction That is, the user interface Controller Processes and responds to events Notifies model of events Typically responds to user input and invokes operation/change on model 33
Observer s Relationship to MVC One way to think about MVC at mid-level design (without the observer pattern): :Model :View (make some change to state) updatebargraph(b) The model keeps track of all views. The model is updated then tells each view that the model was updated updatepiechart(p) 34
Observer s Relationship to MVC One way to think about MVC at mid-level design (without the observer pattern): :Model :View The model keeps track of all views. (make some change to state) updatebargraph(b) updatepiechart(p) The model is updated then tells each view that the model was updated but the whole point of MVC is to remove ties between model and view! 35
Observer s Relationship to MVC MVC design decoupled with the Observer pattern: :Model notify() update() :View The View previously registered interest in changes to model now, the model doesn t need to know anything about the views getdata() it just notifies registered parties of interest when state changes. 36
MVC Solution: Static Structure Observer Model attach (Observer) For all x in observers{ x.update(); } update() detach (Observer) notify () getdata performservice represents View mymodel mycontroller initialize(model) makecontroller activate() display() update() manipulates Controller mymodel mycontroller initialize(model, View) handleevent(event) update() calls-service-on 37
GoF Taxonomy of Design Patterns Behavioral Observer (reactor) Mediator (broker) Structural Adapter (broker) Façade (broker) Proxy (broker) Creational Singleton (generator) Abstract Factory (generator) Categories by GoF, textbook s classification in parentheses 38
Word Processor Example Want to build a word-processor Need to be able to click a save button to save work Need to be able to print a file by clicking print button We have a Button and a ButtonListener class Upon Button click, will notify registered ButtonListeners of event We have a DocManager class already Has a printdocument() method Can t change DocManager; have to use as-is How can we combine these together? 39
The Adapter Pattern Description Convert interface of a class into another interface clients expect Adapter lets classes work together that could not otherwise because of incompatible interfaces Applicability Need to use an existing class whose interface does not match Need to make use of incompatible classes 40
The Adapter Pattern (2) Participants Target (ButtonListener) Defines the domain-specific interface that the Client uses Client (Button) Collaborates with objects conforming to the Target interface Adaptee (DocManager) Defines an existing interface that needs adapting Adapter (a new thing we re creating) Adapts the interface of Adaptee to the Target Interface 41
The Adapter Pattern: Approaches Class Adapter Adapter class is a subclass of adaptee Inherits operations Overrides operations if needed Add new operations to provide new interface Object Adapter Adapter object holds a reference to adaptee Delegates work to adaptee object 42
The Adapter (Class) Pattern 43
The Adapter (Object) Pattern 44
Class Adapter for Word Processor Example Button ButtonListener DocManager MyDocManager buttonpressed(e){ print(); } buttonpressed(event e) 45
The Adapter Pattern: Consequences Consequences Class adapter Adapter commits to the concrete Adapter class Won t work when we want to adapt a class and its subclasses Lets Adapter override some of Adaptee s behavior Introduces only one object, no pointer indirection Cannot block access to public attributes and methods of Adaptee Object adapter Lets a single Adapter work with Adaptee and its subclasses Makes it harder to override Adaptee behavior Would have to create Adaptee subclass, make Adapter call subclass operations 46
Applying the Adapter Pattern Analogy Electrical travel adapters Design example Thread safe PriorityQueue Design choice between Object and Class Adapter Must use Object Adapter if: Adaptee has changeable public attributes Cannot subclass adaptee Cannot override methods of adaptee 47
GoF Taxonomy of Design Patterns Behavioral Observer (reactor) Mediator (broker) Structural Adapter (broker) Façade (broker) Proxy (broker) Creational Singleton (generator) Abstract Factory (generator) Categories by GoF, textbook s classification in parentheses 48
Print Spooler Example Have several printers that can be accessed within a system Print jobs are all served in priority order Ordering can be defined by importance or arrival Need just one print spooler to coordinate access to set of printers 49
The Singleton Pattern Description A software entity must be unique Applicability Only single instance of a class should exist Single instance should be widely accessible Control access to resource 50
The Singleton Pattern Solution Restrict access to constructor Create only a single instance of a class Allow access only to single instance 51
The Singleton Pattern: Static Structure Client Singleton -theinstance : Singleton = null -Singleton() + instance() : Singleton if (theinstance == null) theinstance = new Singleton() return instance 52
The Singleton Pattern Dynamic Behavior :Client Singleton:Class s = instance() opt [no instance] create s: Singleton 53
The Singleton Pattern: Consequences Advantages Easy to implement Singleton classes can be subclassed Design flexibility 54
Summary Patterns Capture reusable elements of design Provide a design vocabulary Pattern repositories can provide inspiration, insight into design problem and solution Patterns are expressed at different levels Architectural styles MVC Design patterns Observer Next time Two important design patterns you should know: Singleton Proxy 55