Design Patterns Lecture Notes - CMSC 433, Spring 2002 by Alan Sussman - Prof. Alan L. Suss, Study notes of Programming Languages

Lecture notes from a university course on design patterns taught by alan sussman during spring 2002 at carnegie mellon university. The notes cover object modeling technique (omt), class diagrams, interaction diagrams, design patterns, iterator, observer, proxy, singleton, abstract factory, adapter, state, and visitor.

Typology: Study notes

Pre 2010

Uploaded on 02/13/2009

koofers-user-az6
koofers-user-az6 🇺🇸

9 documents

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CMSC 433, Spring 2002 - Alan Sussman
(with Bill Pugh & Adam Porter) 1
CMSC433, Spring 2002
OMT and Design Patterns
Alan Sussman
March 21, 2002
CMSC 433, Spring 2002 -Alan Sussman 2
Administrivia
Project 4 due date extended to Friday, April
5
Design pattern readings will be posted
be selective in what you read
CMSC 433, Spring 2002 -Alan Sussman 3
Last time
RMI example
RMIregistry
passing arguments, return values
marshalling/unmarshalling
Serializable vs. Remote
CMSC 433, Spring 2002 -Alan Sussman 4
OMT – Object Modeling
Technique
To denote relationships and interactions
between classes and objects
class diagram depicts classes, their structure,
and static relationships between them
interaction diagram shows flow of requests
between objects (dynamic behavior of classes)
Used to describe behavior of a design
pattern
CMSC 433, Spring 2002 -Alan Sussman 5
Class diagram
Abstract and concrete classes
AbstractClassName
AbstractOperation1()
Type AbstractOperation2()
ConcreteClassName
Operation1()
Type Operation2()
instanceVariable1
Type instanceVariable2
CMSC 433, Spring 2002 -Alan Sussman 6
Class diagram, cont.
Class relationships
Drawing
ColorCreationTool LineShape
Shape
shapes
inheritance
part-of
reference to
instantiates
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Design Patterns Lecture Notes - CMSC 433, Spring 2002 by Alan Sussman - Prof. Alan L. Suss and more Study notes Programming Languages in PDF only on Docsity!

CMSC433, Spring 2002

OMT and Design Patterns

Alan Sussman

March 21, 2002

CMSC 433, Spring 2002 - Alan Sussman 2

Administrivia

  • Project 4 due date extended to Friday, April
  • Design pattern readings will be posted
    • be selective in what you read

CMSC 433, Spring 2002 - Alan Sussman 3

Last time

  • RMI example
    • RMIregistry
    • passing arguments, return values
    • marshalling/unmarshalling
    • Serializable vs. Remote

CMSC 433, Spring 2002 - Alan Sussman 4

OMT – Object Modeling

Technique

  • To denote relationships and interactions

between classes and objects

  • class diagram depicts classes, their structure, and static relationships between them
  • interaction diagram shows flow of requests between objects (dynamic behavior of classes)
  • Used to describe behavior of a design

pattern

CMSC 433, Spring 2002 - Alan Sussman 5

Class diagram

Abstract and concrete classes

AbstractClassName

AbstractOperation1() Type AbstractOperation2()

ConcreteClassName Operation1() Type Operation2() instanceVariable Type instanceVariable

CMSC 433, Spring 2002 - Alan Sussman 6

Class diagram, cont.

Class relationships

Drawing

CreationTool LineShape Color

Shape shapes

inheritance

part-of

instantiates reference to

CMSC 433, Spring 2002 - Alan Sussman 7

Interaction diagram

Design Patterns

CMSC 433, Spring 2002 - Alan Sussman 9

What is a pattern?

  • Patterns = problem/solution pairs in context
  • Patterns facilitate reuse of successful

software architectures and design

  • Not code reuse
    • Instead, solution/strategy reuse
    • Sometimes, interface reuse

CMSC 433, Spring 2002 - Alan Sussman 10

Gang of Four

  • The book that started it all
  • Community refers to authors as the “Gang of Four”
  • Figures and some text in these slides come from book

CMSC 433, Spring 2002 - Alan Sussman 11

Some design patterns

you already know

  • Iterator
    • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • Observer
    • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • Proxy
    • Provide a surrogate or placeholder for another object to control access to it.

CMSC433, Spring 2002

Design Patterns

Alan Sussman

April 2, 2002

CMSC 433, Spring 2002 - Alan Sussman 19

Uses of Iterator Pattern

CMSC 433, Spring 2002 - Alan Sussman 20

You’ve already seen this in Java

  • Iterators for Collections
    • Also, Enumerators for Hashtables and Vectors

CMSC 433, Spring 2002 - Alan Sussman 21

Observer pattern

CMSC 433, Spring 2002 - Alan Sussman 22

Use of an Observer pattern

CMSC 433, Spring 2002 - Alan Sussman 23

Implementation details

  • Observing more than one subject.
    • It might make sense in some situations for an observer to depend on more than one subject. The subject can simply pass itself as a parameter in the Update operation, thereby letting the observer know which subject to examine.
    • Making sure Subject state is self-consistent before notification.

CMSC 433, Spring 2002 - Alan Sussman 24

More Implementation Issues

  • Implementations of the Observer pattern often have the subject broadcast additional information about the change. - At one extreme, the subject sends observers detailed information about the change, whether they want it or not. At the other extreme the subject sends nothing but the most minimal notification, and observers ask for details explicitly thereafter
  • You can extend the subject's registration interface to allow registering observers only for specific events of interest.

CMSC 433, Spring 2002 - Alan Sussman 25

You will see this later in detail

  • MessageListener in project 4 is an example

of the Observer pattern

  • The standard Java and JavaBean event

model is an example of an observer pattern

CMSC 433, Spring 2002 - Alan Sussman 26

Proxy pattern

CMSC 433, Spring 2002 - Alan Sussman 27

Example of Proxy Pattern

CMSC 433, Spring 2002 - Alan Sussman 28

Known uses (from DP book)

  • McCullough [McC87] discusses using proxies in Smalltalk to access remote objects. Pascoe [Pas86] describes how to provide side-effects on method calls and access control with "Encapsulators."
  • NEXTSTEP [Add94] uses proxies (instances of class NXProxy) as local representatives for objects that may be distributed. - On receiving a message, the proxy encodes it along with its arguments and then forwards the encoded message to the remote subject. Similarly, the subject encodes any return results and sends them back to the NXProxy object.

CMSC 433, Spring 2002 - Alan Sussman 29

Creation patterns

  • Singleton
    • Ensure a class only has one instance, and provide a global point of access to it.
  • Abstract Factory
    • Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

CMSC 433, Spring 2002 - Alan Sussman 30

Structural patterns

  • Adapter
    • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

CMSC433, Spring 2002

Design Patterns

Alan Sussman

April 4, 2002

CMSC 433, Spring 2002 - Alan Sussman 38

Administrivia

  • Project 4 due Friday
  • Project 5 posted soon
    • talk about it on Tuesday
  • Project 3 commentary due Wed., April 10

CMSC 433, Spring 2002 - Alan Sussman 39

Last time

  • Design patterns
    • Iterator – as in Java collection classes
    • Observer – as in event listeners for GUIs
    • Proxy – like web proxies
    • Singleton – like myCounter

CMSC 433, Spring 2002 - Alan Sussman 40

Abstract Factory

  • Different look-and-feels define different

appearances and behaviors for user interface

“widgets” like scroll bars, windows, and

buttons.

CMSC 433, Spring 2002 - Alan Sussman 41

Using an abstract factory

  • Get a reference to a type WidgetFactory
    • To an object of the appropriate subtype of WidgetFactory
    • Ask the WidgetFactory for a scroll bar, or for a window

CMSC 433, Spring 2002 - Alan Sussman 42

Adapter pattern

  • Clients needs a target that implements one

interface

CMSC 433, Spring 2002 - Alan Sussman 43

JDK 1.3 Proxy class

  • Can be used for both Proxy and Adapter

pattern

  • Use java.lang.reflect.Proxy
  • Create object that implements a set of

interfaces

  • Specified dynamically
  • Invocation handler handles calls

CMSC 433, Spring 2002 - Alan Sussman 44

State pattern

  • Suppose an object is always in one of

several known states

  • The state an object is in determines the

behavior of several methods

  • Could use if/case statements in each method
  • Better solution: state pattern

CMSC 433, Spring 2002 - Alan Sussman 45

State pattern

  • Have a reference to a state object
    • Normally, state object doesn’t contain any fields
    • Change state: change state object
    • Methods delegate to state object

CMSC 433, Spring 2002 - Alan Sussman 46

Structure of State pattern

CMSC 433, Spring 2002 - Alan Sussman 47

Instance of State Pattern

CMSC 433, Spring 2002 - Alan Sussman 48

State pattern notes

  • Can use singletons for instances of each

state class

  • State objects don’t encapsulate state, so can be shared
  • Easy to add new states
  • New states can extend other states
  • Override only selected functions

CMSC 433, Spring 2002 - Alan Sussman 55

Using overloading in a visitor

  • You can name all of the visitXXX(XXX x)

methods just visit(XXX x)

  • Calls to Visit (AssignmentNode n) and Visit(VariableRefNode n) distinguished by compile-time overload resolution

CMSC 433, Spring 2002 - Alan Sussman 56

Easy to provide default behavoir

  • Default

visit(BinaryPlusOperatorNode)

can just forward call to

visit(BinaryOperatorNode)

  • Visitor can just provide implementation of

visit(BinaryOperatorNode) if it doesn’t care

what type of binary operator node it is at

CMSC 433, Spring 2002 - Alan Sussman 57

State in a visitor pattern

  • A visitor can contain state
    • E.g., the results of parsing the program so far
  • Or use stateless visitors and pass around a

separate state object

CMSC433, Spring 2002

Design Patterns

Alan Sussman

April 9, 2002

CMSC 433, Spring 2002 - Alan Sussman 59

Administrivia

  • Project 3 commentary due tomorrow
  • Project 5 posted
    • redo Project 3, in parts
  • One more design pattern today, then back to

concurrent programming, from Lea book

  • read Ch. 1 if you haven’t already

CMSC 433, Spring 2002 - Alan Sussman 60

Last time

  • Design patterns
    • Abstract factory
    • Adaptor
    • State
    • Visitor

CMSC 433, Spring 2002 - Alan Sussman 61

Traversals

  • In the standard visitor pattern, the visitor at a node is responsible for visiting the components (i.e., children) of that node - if that is what is desired - Visitors can be applied to flat object structures
  • Several other solutions
    • acceptAndTraverse methods
    • Visit/process methods
    • traversal visitors applying an operational visitor

Reactor Pattern

CMSC 433, Spring 2002 - Alan Sussman 63

Intent

  • The Reactor architectural pattern allows

event-driven applications to

  • demultiplex and dispatch service requests
  • delivered to an application from one or more clients
  • Also known as
  • Dispatcher, Notifier

CMSC 433, Spring 2002 - Alan Sussman 64

Forces

  • A good solution must resolve the following forces:
    • To enhance scalability and minimize latency, an application must not block indefinitely waiting on any single source
    • To maximize throughput, unnecessary utilization of the CPU(s) should be avoided
    • Minimal modifications and maintenance effort should be required to integrate new or enhanced services

CMSC 433, Spring 2002 - Alan Sussman 65

Solution

  • Synchronously await indication events on

one or more event sources

  • Integrate the mechanisms that demultiplex

events and dispatch them to processing

elements

  • Decouple these from application-specific

processing elements

CMSC 433, Spring 2002 - Alan Sussman 66

Applicability

  • Use Reactor Pattern when a process is

event-driven and:

  • Threading leads to poor performance
  • Threading requires complex concurrency control
  • OS does not support multiple threading within a process

Design Patterns Again

CMSC 433, Spring 2002 - Alan Sussman 74

Why patterns?

  • Sometimes, patterns are just a cool idea you might not have come up with on your own - Learn from others
  • If you work with code written by someone else
    • If they use a pattern you know, it will be easier for you to understand their code
  • Some frameworks can automatically build/manipulate certain design patterns

CMSC 433, Spring 2002 - Alan Sussman 75

Pattern hype

  • Patterns get a lot of hype and fanatical believers
    • We are going to have a design pattern reading group, and this week we are going to discuss the Singleton Pattern!
  • Patterns are sometimes wrong (e.g., double- checked locking) or inappropriate for a particular language or environment - Patterns developed for C++ can have very different solutions in Smalltalk or Java

More on visitor traversals

CMSC 433, Spring 2002 - Alan Sussman 77

Traversals

  • In the standard visitor pattern, the visitor at a node is responsible for visiting the components (i.e., children) of that node - if that is what is desired - Visitors can be applied to flat object structures
  • Several other solutions
    • acceptAndTraverse methods
    • Visit/process methods
    • traversal visitors applying an operational visitor

CMSC 433, Spring 2002 - Alan Sussman 78

acceptAndTraverse methods

  • accept method could be responsible for

traversing children

  • Assumes all visitors have same traversal pattern
    • E.g., visit all nodes in pre-order traversal
  • Could provide previsit and postvisit methods to allow for more complicated traversal patterns - Still visit every node - Can’t do out of order traversal - In-order traversal requires inVisit method

CMSC 433, Spring 2002 - Alan Sussman 79

Accept and traverse

  • Class BinaryPlusOperatorNode {

void accept(Visitor v) {

v->visit(this);

lhs->accept(v);

rhs->accept(v);

CMSC 433, Spring 2002 - Alan Sussman 80

Visitor/process methods

  • Can have two parallel sets of methods in visitors
    • Visit methods
    • Process methods
  • Visit method on a node:
    • Calls process method of visitor, passing node as an argument
    • Calls accept on all children of the node (passing the visitor as an argument

CMSC 433, Spring 2002 - Alan Sussman 81

Preorder visitor

  • Class PreorderVisitor {

void visit(BinaryPlusOperatorNode n) {

process(n);

n->lhs->accept(this);

n->rhs->accept(this);

CMSC 433, Spring 2002 - Alan Sussman 82

Visit/process, continued

  • Can define a PreorderVisitor
    • Extend it, and just redefine process method
      • Except for the few cases where something other than preorder traversal is required
  • Can define other traversal visitors as well
    • E.g., PostOrderVisitor

CMSC 433, Spring 2002 - Alan Sussman 83

Traversal visitors applying an

operational visitor

  • Define a Preorder traversal visitor
    • Takes an operational visitor as an argument when created
  • Perform preorder traversal of structure
    • At each node
      • Have node accept operational visitor
      • Have each child accept traversal visitor

CMSC 433, Spring 2002 - Alan Sussman 84

PreorderVisitor with payload

  • Class PreorderVisitor {

Visitor payload;

void visit(BinaryPlusOperatorNode n) {

payload->visit(n);

n->lhs->accept(this);

n->rhs->accept(this);