lecture 20: design patterns ii - unc charlotte...prototype singleton adapter (object) bridge...

53
Lecture 20: Design Patterns II Software System Design and Implementation ITCS/ITIS 6112/8112 001 Fall 2008 Dr. Jamie Payton Department of Computer Science University of North Carolina at Charlotte Nov. 13, 2008

Upload: others

Post on 21-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

Lecture 20:Design Patterns II

Software System Design and ImplementationITCS/ITIS 6112/8112 001

Fall 2008

Dr. Jamie PaytonDepartment of Computer Science

University of North Carolina at Charlotte

Nov. 13, 2008

Page 2: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

2

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

Page 3: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

3

Alexander’s Patterns

Different Chairs (251)...People are different sizes; they sit in different ways. And yet there is a tendency in modern times to make all chairs alike. ...therefore Never furnish any place with chairs that are identically the same. Choose a variety of different chairs, some big, some small, somesofter than others, some rockers, some very old, some new, with arms, without arms, some wicker, some wood, some cloth.

Page 4: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

4

Pattern Elements

NameA meaningful pattern identifier

Problem description (Applicability)Solution description

Not a concrete design……instead, a template for a design solution

ConsequencesThe results and trade-offs of applying the pattern

Page 5: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

5

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 6: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

6

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 7: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

7

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 8: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

8

Scope Purpose

Creational Structural Behavioral

Class Factory Method Adapter (class) InterpreterTemplate Method

Object Abstract FactoryBuilderPrototypeSingleton

Adapter (object)BridgeCompositeDecoratorFaçadeProxyFlyweight

Chain of ResponsibilityCommandIteratorMediatorMementoObserverStateStrategyVisitor

Page 9: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

9

Boggle

Let’s design an networked Boggle gamePlayers find words in the jumble of letters on the board within given time framePlayer gets one point for each identified real word that is unique• unique = not found by another player

Player with most points wins

What are the basic classes? (ignore the user interface for now)

How do they work together?How should we keep score?

Page 10: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

10

Scoring in the Players

Problems?Now every player object has to know about:• Board• Player• Dictionary• EVERY OTHER PLAYER

Tightly coupled!!!

Scoring algorithm is in the player class• May not be the best place for it

Not cohesive!!!

Page 11: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

11

Mediator Pattern (1)

ApplicabilityComplex interaction existsYou do not want to bury the interaction in the objectsDistributed behavior should be customizable

SolutionIntroduce a mediator class that is responsible for controlling and coordinating group of objectsObjects refer only to mediator, not each other

Page 12: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

12

Mediator (2)

ParticipantsMediator (interface)• Defines interface for communicating with Colleagues

Concrete Mediator• Coordinates Colleague objects• Knows and maintains Colleagues

Colleague• Each Colleague knows its Mediator• Each Colleague communicates with Mediator instead of

Colleagues

Page 13: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

13

Mediator (3)

ConsequencesDecouples colleaguesAbstracts how objects cooperateCentralizes control • Simplifies object interaction protocols…• …but can cause a performance hit

Mediator can become complex and unwieldy

Page 14: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

14

The Mediator Pattern:Static Structure

Page 15: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

15

Mediator-driven Scoring

Page 16: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

16

Comparing Boggle Scoring Design Approaches

Without mediatorEach Player must have references to Board, Dictionary, and all Player objects to do scoringScoring algorithm is in Player class• May not really belong there• Complicates Player class

With MediatorPlayer needs references to Board and Tiles only to make playsScoring is in Scorer class• More logically organized, easier to make changes

Page 17: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

17

Applying the Mediator Pattern

AnalogiesMeeting SchedulerEmergency Call DispatcherAir Traffic Control CenterChat ApplicationsBoggle

Page 18: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

18

Types of Patterns

BehavioralObserverMediator

StructuralFaçadeAdapterProxy

CreationalAbstract Factory

Page 19: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

19

Compiler Example

A compilation subsystem consists of:ScannerParserProgramNodeBytecodeStreamProgramNodeBuilder

Most applications that use the compilation subsystem don’t care about the details of these classes

Complicated if the clients have to use the classes directly

Page 20: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

20

The Façade Pattern (1)

DescriptionProvide a unified interface to a set of interfaces in a subsystemFacade defines a higher-level interface that makes the subsystem easier to use

Page 21: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

21

The Façade Pattern (2)

ApplicabilityNeed to provide a simple interface to a complex systemNeed to decouple a subsystem from its clientsWant to treat subsystem as a software layer• Façade is used as interface to a software layer

Page 22: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

22

The Façade Pattern (3)

ParticipantsFaçade• Knows which subsystems classes are responsible for handling a

particular request• Delegates client requests to appropriate subsystem objects

Subsystem classes• Implement subsystem functionality• Handle work assigned by Facade• Have no knowledge of Facade

Page 23: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

23

The Façade Pattern (4)

ConsequencesShields clients from subsystem componentsPromotes weak coupling between the subsystem and its clients• Shield clients from changes to subsystems

Only Façade needs to be aware of changes

Page 24: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

24

Facade Pattern: Solution

Client Classes

Subsystem classes

Facade

Page 25: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

25

Façade Example

AnalogyTravel agent

Design ExampleA friendlier Java Calendar class

Page 26: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

26

Mediator and Façade

Mediator coordinates interaction among multiple objects

Defines some function that is not in ColleaguesColleagues know about Mediator

Façade provide a simplified interface to subsystemsSubsystems do not know about Façade

Can think of a Mediator as a multi-way FaçadeObjects involved in interaction subsystemObjects interact with subsystem through Mediator

Page 27: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

27

Types of Patterns

BehavioralObserverMediator

StructuralFaçadeAdapterProxy

CreationalAbstract Factory

Page 28: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

28

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 29: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

29

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 30: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

30

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 31: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

31

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 32: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

32

The Adapter (Class) Pattern

Page 33: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

33

The Adapter (Object) Pattern

Page 34: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

34

Class Adapter for Word Processor Example

Button ButtonListener DocManager

MyDocManager

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

Page 35: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

35

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 36: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

36

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 37: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

37

Adapter versus Facade

Façade Used to provide a simplified interface to a subsystem

AdapterUsed to provide a different interface to a single classUsed when operations with slightly different functionality are needed

Page 38: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

38

Types of Patterns

BehavioralObserverMediator

StructuralFaçadeAdapterProxy

CreationalAbstract Factory

Page 39: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

39

The Proxy PatternDescription

Provide a placeholder for another object Applicability

Remote proxies• Hide location of objectVirtual proxies • Create expensive objects on demandProtection proxies • Control access to an objectSmart proxies may: • Count number of references to object (so it can be freed)• Load persistent object into memory on first reference• Prevent changes by other objects

Page 40: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

40

The Proxy Pattern

Page 41: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

41

Proxy Examples

AnalogyATM card substitutes for cashManager sends subordinate to meeting

Design exampleImage manipulation

Page 42: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

42

Types of Patterns

BehavioralDescribe how classes interact and distribute responsibility• Observer• Mediator

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

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

Page 43: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

43

Traffic Simulator

Want to design a traffic simulator to study traffic patterns

We have Road and VehiclesVehicles are of different types• SUV• Compact• MiniVan• MidSizeVehicles should be generated to match expected distributionWhich class should do this?• Road?• Class?• Neither, really

Page 44: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

44

The Factory Method Pattern

ApplicabilityClients do not need to know details of object implementation, just need it to implement particular interface

ConsequencesClient does not have to create objects• Created by generator

Allows choice of actual object type at runtime

Page 45: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

45

Factory ExamplesAnalogy

Automobile production• SUVs: Ford Explorer, Acura MDX, Subaru OutbackRental car company• Ask for a compact car, but you don’t care if it’s a Civic

Design ExampleVehicle traffic simulator• Vehicle and Road classes• Must randomly create new Vehicle to adhere to expected distribution of

vehicle typesCompact, SUV, Minivan, Truck

• Which class chooses Vehicle type?Road? VehicleFactory!

Page 46: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

46

Types of Patterns

BehavioralObserverMediator

StructuralFaçadeAdapterProxy

CreationalFactoryAbstract Factory

Page 47: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

47

The Abstract Factory Pattern

DescriptionProvides an interface for creating families of related or dependent objects without specifying their concrete classes

Page 48: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

48

The Abstract Factory Pattern (2)

ApplicabilityNeed to abstract from details of implementation of products Need to have multiple families of products Need to enforce families of products that must be used together Need to hide product implementations and just present interfaces

ConsequencesIsolates concrete classes Makes exchanging product families easy Promotes consistency among products Supporting new kinds (in each family) of products is difficult

Page 49: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

49

The Abstract Factory Pattern

AbstractFactory

CreateProductA()

CreateProductB()

ConcreteFactory1

Client

ProductA1ProductA2

AbstractProductA

ProductB2 ProductB1

AbstractProductB

ConcreteFactory2

CreateProductA()

CreateProductB()

Page 50: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

50

Abstract Factory Example

WidgetFactory

CreateScrollbar()

CreateWindow()

Window

ScrollBarWWidgetFactory

MacWidgetFactory

Client

WWindowMacWindow

MacScrollBar WScrollBar

One for each standard.

Page 51: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

51

Factory Method versus Abstract Factory

Abstract Factory uses Factory Method

Page 52: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

52

Design patterns are generic, reusable design templatesDesign patterns provide a vocabulary for discussing designThree types of patterns

BehavioralStructuralCreational

Summary

Page 53: Lecture 20: Design Patterns II - UNC Charlotte...Prototype Singleton Adapter (object) Bridge Composite Decorator Façade Proxy Flyweight Chain of Responsibility Command Iterator Mediator

53

Resources

Introduction to Software Engineering DesignChristopher Fox

GoF bookPoSA bookArticles posted on course website