55
1 Software Engineering ITCS 3155 Fall 2008 Dr. Jamie Payton Department of Computer Science University of North Carolina at Charlotte Dec. 2, 2008 Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns

Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

1

Software EngineeringITCS 3155Fall 2008

Dr. Jamie PaytonDepartment of Computer ScienceUniversity of North Carolina at Charlotte

Dec. 2, 2008

Lectures 24 and 25Introduction to Architectural Styles and

Design Patterns

Page 2: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

22

AnnouncementsDeliverable 3

Extensions: due Dec. 2 at 11:59 pm (tonight)Assessments• Extensions: due Dec. 3 at 11:59 pm• Use new links

Sent by emailPosted on website

Final examDec. 16 at 11:30 amExam review• In class on Dec. 9• Come to class prepared with questions

Extra creditAttend ACM Distinguished Speaker talk • Friday, Dec. 5 at 3:00 pm • Woodward 106• Sign in with me to get extra credit

Page 3: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

33

Lecture Overview

ResourcesChapter 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

Page 4: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4

Software Design Patterns

A pattern is a way of reusing abstract knowledge about design

a description of the problemthe essence of its solution

Patterns allow programmers to share knowledge about design

Provide a shared design vocabulary

Page 5: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

5

History of Design PatternsArchitect 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 disorientedCreate pools of light, will result in pleasant gathering places

Page 6: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

6

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 moreConferences, symposia, other books

Page 7: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

7

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-systemsDesign patterns• Involve several interacting classes or operationsData structures & algorithms• Low-level, detailed design patternsIdioms• Ways of doing things that are specific to a programming

language

Page 8: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

8

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 stylesLayered architecturePipe and filterShared dataEvent drivenModel View Controller (MVC)

Page 9: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

9

Example:Information System for Political Elections

A=10%B=40%C=30%D=20%

Application data

A

BC

D

A DCB

Relative Percentages

Y 10 40 30 20

X 15 35 35 15

Z 10 40 30 20

A B C D

Change notification

Requests, modifications

Page 10: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

10

Architectural Style Example:Model-View-Controller (MVC)

ApplicabilityInteractive 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

Page 11: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

11

Model-View-Controller (MVC)

Solution: separate the data being manipulated from the manipulation logic and the details of displayThree 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

Page 12: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

12

MVC Participants and Responsibilities

View Each view is associated with a controller Each view is associated with the modelUser interacts with system only through a view’s controllerDefines 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

Page 13: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

13

MVC Participants and Responsibilities

ModelIf model is updated, model notifies all interested parties (registered views and possibly controllers) of changeViews will retrieve new data from model and update displayed information

Page 14: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

14

MVC Solution:Static Structure

Page 15: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

15

MVC Solution:Behavior

Page 16: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

16

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 executionUser interface components can be changed, even at runtime

Page 17: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

17

Consequences:MVC Disadvantages

Views and controller are often hard to separateFrequent updates may slow data display and degrade user interface performanceThe MVC style makes user interface components (views, controllers) highly dependent on model components

Page 18: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

18

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

Page 19: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

19

Design Pattern Elements

NameA 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

ConsequencesThe results and trade-offs of applying the pattern

Page 20: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

2020

Purpose of Patterns

BehavioralDescribe how classes or objects interact and distribute responsibility• Observer (last time)• Mediator

StructuralDescribe how classes or objects should be composed• Façade• Adapter• Proxy

CreationalConcern the process of object creation• Factory method• Abstract Factory

Page 21: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

2121

Scope of Patterns

ScopeAnother dimension for classifying patternsClass patterns• Relationships between classes and subclasses

Established through inheritanceFixed at compile-time

Object patterns• Relationships between objects

Changeable at run-time(most patterns)

Page 22: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

2222

Purpose and ScopeBehavioral

Class• Use inheritance to describe algorithms and flow of controlObject• Describe how a group of objects cooperate to perform a task

StructuralClass• Use inheritance to compose classesObject• Describe how to compose objects

CreationalClass• Defer some part of object creation to a subclassObject• Defer some part of object creation to another object

Page 23: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

2323

Scope Purpose

Creational Structural Behavioral

Class Factory Method Adapter (class) InterpreterTemplate Method

Object Abstract FactoryBuilderPrototypeSingleton

Adapter (object)BridgeCompositeDecoratorFaçadeProxyFlyweight

Chain of ResponsibilityCommandIteratorMediatorMementoObserverStateStrategyVisitor

Page 24: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

24

Textbook Classification

Broker patternsa client needs a service from a suppliera broker mediates interaction between client and supplier

Generator patternsa client needs a new instance of a producta generator class supplies the instance

Reactor patternsa client needs to respond to an event in a targetclient delegates this responsibility to a reactor

Page 25: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

25

Category Analogies

Brokersstock brokers who mediate interactions between an investor (client) and the stock market (supplier)

Generatorsinterior 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).

Page 26: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

26

GoF Taxonomy of Design Patterns

BehavioralObserver (reactor)Mediator (broker)

StructuralAdapter (broker)Façade (broker)Proxy (broker)

CreationalSingleton (generator)Abstract Factory (generator)

Categories by GoF, textbook’s classification in parentheses

Page 27: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

2727

Patterns by Example:Multiple Displays Enabled by Observer

A=10%B=40%C=30%D=20%

Application data

A

BC

D

A DCB

Relative Percentages

Y 10 40 30 20

X 15 35 35 15

Z 10 40 30 20

A B C D

Change notification

Requests, modifications

Page 28: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

28

Behavioral Pattern Example:The Observer Pattern

NameObserver

DescriptionReduces coupling between interacting classes

Problem descriptionUsed when one or more observers must track changes to an object

Solution descriptionUse a change-propagation mechanism between info provider (subject) and the components that use it to display (observers)• The register and notify approach !!!

Page 29: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

2929

The Observer Pattern

NameObserver• a.k.a. publish-subscribe

Description/ApplicabilityGeneral: 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 descriptionUsed when multiple displays of state are needed• need changes to state to be reflected consistently across all displays

Page 30: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

3030

The Observer Pattern

Solution descriptionUse a change-propagation mechanism between info provider (subject) and the components that use it to display (observers)• Subject

Stores state of interestProvides ability for Observers to attach/detachCalls Observer’s update interface

• ObserverProvides an update interfaceAttaches and detaches itself from Subject

Page 31: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

3131

The Observer Pattern

Subject

attach (Observer)

detach (Observer)

notify ()

Observer

update()

Concrete Observer

observerStateConcrete Subject

getState()setState()

subjectState

For all x in observers{x.update(); }

observerState=subject getState();

Page 32: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

32

Observer Pattern

ConsequencesCan add/remove observers at any time without modifying subjectCan reuse subjects without reusing observers (and vice-versa)Unexpected updates to subject can cause a cascade of unnecessary update operations on observer

32

Page 33: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

3333

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 operationsView• 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

Page 34: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

34

Observer’s Relationship to MVC

One way to think about MVC at mid-level design (without the observer pattern):

The model keeps track of all views.

The model is updated then tells each view that the model was updated…

:Model :View

updateBarGraph(b)

updatePieChart(p)

(make some change to state)

Page 35: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

35

Observer’s Relationship to MVC

One way to think about MVC at mid-level design (without the observer pattern):

The model keeps track of all views.

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!

:Model :View

updateBarGraph(b)

updatePieChart(p)

(make some change to state)

Page 36: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

36

Observer’s Relationship to MVC

MVC design decoupled with the Observer pattern:

The View previously registered interest in changes to model…

…now, the model doesn’t need to know anything about the views…

…it just notifies registered parties of interest when state changes.

:Model :View

update()

getData()

notify()

Page 37: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

3737

MVC Solution:Static Structure Observer

update()

View

myModel

myController

initialize(Model)makeControlleractivate()display()update()

For all x in observers{x.update(); }

Model

attach (Observer)

detach (Observer)notify ()getDataperformService

Controller

myModel

myController

initialize(Model, View)handleEvent(Event)update()

represents

manipulates

calls-service-on

Page 38: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

38

GoF Taxonomy of Design Patterns

BehavioralObserver (reactor)Mediator (broker)

StructuralAdapter (broker)Façade (broker)Proxy (broker)

CreationalSingleton (generator)Abstract Factory (generator)

Categories by GoF, textbook’s classification in parentheses

Page 39: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

3939

Word Processor Example

Want to build a word-processorNeed to be able to click a “save” button to save workNeed 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 alreadyHas a printDocument() methodCan’t change DocManager; have to use as-is

How can we combine these together?

Page 40: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4040

The Adapter Pattern

DescriptionConvert interface of a class into another interface clients expectAdapter lets classes work together that could not otherwise because of incompatible interfaces

ApplicabilityNeed to use an existing class whose interface does not matchNeed to make use of incompatible classes

Page 41: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4141

The Adapter Pattern (2)

ParticipantsTarget (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

Page 42: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4242

The Adapter Pattern: Approaches

Class AdapterAdapter class is a subclass of adaptee• Inherits operations• Overrides operations if needed• Add new operations to provide new interface

Object AdapterAdapter object holds a reference to adaptee• Delegates work to adaptee object

Page 43: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4343

The Adapter (Class) Pattern

Page 44: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4444

The Adapter (Object) Pattern

Page 45: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4545

Class Adapter for Word Processor Example

Button ButtonListener DocManager

MyDocManager

buttonPressed(Event e)buttonPressed(e){print();…}

Page 46: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4646

The Adapter Pattern:Consequences

ConsequencesClass 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

AdapteeObject 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

Page 47: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

4747

Applying the Adapter Pattern

AnalogyElectrical travel adapters

Design exampleThread safe PriorityQueue

Design choice between Object and Class Adapter• Must use Object Adapter if:

Adaptee has changeable public attributesCannot subclass adapteeCannot override methods of adaptee

Page 48: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

48

GoF Taxonomy of Design Patterns

BehavioralObserver (reactor)Mediator (broker)

StructuralAdapter (broker)Façade (broker)Proxy (broker)

CreationalSingleton (generator)Abstract Factory (generator)

Categories by GoF, textbook’s classification in parentheses

Page 49: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

49

Print Spooler Example

Have several printers that can be accessed within a systemPrint 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

Page 50: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

50

The Singleton Pattern

DescriptionA software entity must be unique

ApplicabilityOnly single instance of a class should existSingle instance should be widely accessibleControl access to resource

50

Page 51: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

51

The Singleton Pattern

SolutionRestrict access to constructorCreate only a single instance of a classAllow access only to single instance

51

Page 52: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

52

The Singleton Pattern:Static Structure

52

ClientSingleton

-theInstance : Singleton = null

-Singleton()+ instance() : Singleton

if (theInstance == null)theInstance = new Singleton()

return instance

Page 53: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

53

The Singleton PatternDynamic Behavior

53

:Client Singleton:Class

s = instance()

s: Singletoncreate[no instance]opt

Page 54: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

54

The Singleton Pattern:Consequences

AdvantagesEasy to implementSingleton classes can be subclassed• Design flexibility

54

Page 55: Lectures 24 and 25 Introduction to Architectural Styles and Design … · In other words, a pattern of decomposition of major software parts and their relationships, responsibilities,

55

Summary

PatternsCapture reusable elements of designProvide a design vocabularyPattern repositories can provide inspiration, insight into design problem and solution

Patterns are expressed at different levelsArchitectural styles• MVCDesign patterns• Observer

Next timeTwo important design patterns you should know:• Singleton• Proxy