0% found this document useful (0 votes)
279 views

What Is A Pattern?

The document discusses design patterns including the Iterator, Observer, Proxy, Singleton, and Abstract Factory patterns. It provides brief descriptions of each pattern, examples of how they are used, and implementation details. Design patterns facilitate reuse of successful software architectures and solutions to common problems, rather than code reuse directly. The Gang of Four book that introduced many classic design patterns is referenced throughout.

Uploaded by

karthi8005759394
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
279 views

What Is A Pattern?

The document discusses design patterns including the Iterator, Observer, Proxy, Singleton, and Abstract Factory patterns. It provides brief descriptions of each pattern, examples of how they are used, and implementation details. Design patterns facilitate reuse of successful software architectures and solutions to common problems, rather than code reuse directly. The Gang of Four book that introduced many classic design patterns is referenced throughout.

Uploaded by

karthi8005759394
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

What is a pattern?

• Patterns = problem/solution pairs in context


• Patterns facilitate reuse of successful
Design Patterns software architectures and design
• Not code reuse
CMSC 433 – Instead, solution/strategy reuse
– Sometimes, interface reuse

Design patterns, CMSC 433 2

Some design patterns


Gang of Four
you already know
• The book that started • Iterator
it all – Provide a way to access the elements of an aggregate
object sequentially without exposing its underlying
• Community refers to representation.
authors as the “Gang • Observer
of Four” – Define a one-to-many dependency between objects so
• Figures and some text that when one object changes state, all its dependents
are notified and updated automatically.
in these slides come
from book • Proxy
– Provide a surrogate or placeholder for another object to
control access to it.

Design patterns, CMSC 433 3 Design patterns, CMSC 433 4

Iterator pattern Uses of Iterator Pattern

Design patterns, CMSC 433 5 Design patterns, CMSC 433 6

1
You’ve already seen this in Java Observer pattern
• Iterators for Collections
– Also, Enumerators for Hashtables and Vectors

Design patterns, CMSC 433 7 Design patterns, CMSC 433 8

Use of an Observer pattern 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.

Design patterns, CMSC 433 9 Design patterns, CMSC 433 10

More Implementation Issues You’ve seen this before


• Implementations of the Observer pattern often • The standard Java and JavaBean event
have the subject broadcast additional information model is an example of an observer pattern
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.

Design patterns, CMSC 433 11 Design patterns, CMSC 433 12

2
Proxy pattern Example of Proxy Pattern

Design patterns, CMSC 433 13 Design patterns, CMSC 433 14

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." Some new patterns
• 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.
Design patterns, CMSC 433 15

Creation patterns Structural patterns


• Singleton • Adapter
– Ensure a class only has one instance, and – Convert the interface of a class into another
provide a global point of access to it. interface clients expect. Adapter lets classes
• Abstract Factory work together that couldn't otherwise because
of incompatible interfaces.
– Provide an interface for creating families of
related or dependent objects without specifying
their concrete classes.

Design patterns, CMSC 433 17 Design patterns, CMSC 433 18

3
Behavioral patterns Singleton pattern
• State • It's important for some classes to have
– Allow an object to alter its behavior when its exactly one instance
internal state changes. The object will appear to
– Many printers, but only one print spooler
change its class.
– One file system
• Visitor
– Represent an operation to be performed on the – One window manager
elements of an object structure. Visitor lets you • Such designs can be limiting
define a new operation without changing the
classes of the elements on which it operates.

Design patterns, CMSC 433 19 Design patterns, CMSC 433 20

Implementing the
The Singleton solution
Singleton method
• Make the class itself responsible for • In Java, just define a final static field
keeping track of its sole instance. Class Singleton {
private Singleton() {…}
• Make constructor private public final static Singleton instance
• Provide static method/field to allow access = new Singleton();
to the only instance of the class …
}
• Java semantics guarantee object is created
immediately before first use

Design patterns, CMSC 433 21 Design patterns, CMSC 433 22

Implementing the Singleton Implementing the Singleton


Method in C++ Method in C++
• C++ static initialization is very limited and Class Singleton {
ill-defined private: Singleton() {…}
static Singleton _instance = 0;
• Use instance() method public: static Singleton instance() {
if (_instance == 0)
• Note: not thead safe _instance = new Singleton();
– Java method is thread safe return _instance;
}

}

Design patterns, CMSC 433 23 Design patterns, CMSC 433 24

4
Abstract Factory Using an abstract factory
• Different look-and-feels define different
appearances and behaviors for user interface • Get a reference to of type WidgetFactory
“widgets” like scroll bars, windows, and – To an object of the appropriate subtype of
WidgetFactory
buttons.
– Ask the WidgetFactory for a scroll bar, or for a
window

Design patterns, CMSC 433 25 Design patterns, CMSC 433 26

Adapter pattern Structure of Adapter pattern


• Clients needs a target that implements one
interface
• Provider doesn’

Design patterns, CMSC 433 27 Design patterns, CMSC 433 28

JDK 1.3 Proxy class State pattern


• Can be used for both Proxy and Adaptor • Suppose an object is always in one of
pattern several known states
• Use java.lang.reflect.Proxy • The state an object is in determines the
• Create object that implements a set of behavior of several methods
interfaces • Could use if/case statements in each method
– Specified dynamically • Better solution: state pattern
– Invocation handler handles calls

Design patterns, CMSC 433 29 Design patterns, CMSC 433 30

5
State pattern Structure of 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

Design patterns, CMSC 433 31 Design patterns, CMSC 433 32

Instance of State Pattern State pattern notes


• Can use singletons for instances of each state class
– State objects don’t encapsulate state, so can be shared
• Or use inner classes
– Each state object contains reference to outer object
• Easy to add new states
– New states can extend other states
• Override only selected functions

Design patterns, CMSC 433 33 Design patterns, CMSC 433 34

Visitor pattern Not a visitor


• A visitor encapsulates the operations to be
performed on a entire structure
– E.g., all elements of a parse tree
• Allows them to be specified separately from
the parse tree
– But doesn’t require putting all of the structure
traversal code into each visitor/operation

Design patterns, CMSC 433 35 Design patterns, CMSC 433 36

6
Double-dispatch
Visitor pattern
• Accept code is always trivial
– Just dynamic dispatch on argument, with
runtime type of structure node taking into
account in method name
• A way of doing double-dispatch
– Dynamic dispatching on the run-time types of
two arguments
– Visitor code invoked depends on run-time type
of both visitor and node

Design patterns, CMSC 433 37 Design patterns, CMSC 433 38

Using overloading in a visitor Can provide default behavoir


• You can name all of the visitXXX(XXX x) • Default
methods just visit(XXX x) visit(BinaryPlusOperatorNode)
– Calls to Visit (AssignmentNode n) can just forward call to
and Visit(VariableRefNode n) distinguished visit(BinaryOperatorNode)
compile-time overload resolution • Visitor can just provide implementation of
visit(BinaryOperatorNode) if it doesn’t care
what type of binary operator node it is at

Design patterns, CMSC 433 39 Design patterns, CMSC 433 40

State in a visitor pattern Traversals


• Visitor’s can contain state • In the standard visitor pattern, the visitor at a node
– E.g., the results of parsing the program so far is responsible for visiting the components (i.e.,
children) of that node
• Or use stateless visitors and pass around a – if that is what is desired
separate state object • Visitors can be applied to flat object structures
• Several solutions
– acceptAndTraverse methods
– Visit/process methods
– traversal visitors applying a operational visitor

Design patterns, CMSC 433 41 Design patterns, CMSC 433 42

7
acceptAndTraverse methods Accept and traverse
• accept method could be responsible for • Class BinaryPlusOperatorNode {
traversing children void accept(Visitor v) {
– Assumes all visitors have same traversal pattern v->visit(this);
• E.g., visit all nodes in pre-order traversal
lhs->accept(v);
– Could provide previsit and postvisit methods to
allow for more complicated traversal patterns
rhs->accept(v);
• Still visit every node }
• Can’t do out of order traversal …}
• In-order traversal requires inVisit method

Design patterns, CMSC 433 43 Design patterns, CMSC 433 44

Visitor/process methods Preorder visitor


• Can have two parallel sets of methods in visitors • Class PreorderVisitor {
– Visit methods void visit(BinaryPlusOperatorNode n) {
– Process methods process(n);
• Visit method on a node: n->lhs->accept(this);
– Calls process method of visitor, passing node as an n->rhs->accept(this);
argument
– Calls accept on all children of the node (passing the
}
visitor as an argument …}

Design patterns, CMSC 433 45 Design patterns, CMSC 433 46

Traversal visitors applying an


Visit/process, continued
operational visitor
• Can define a PreorderVisitor • Define a Preorder traversal visitor
– Extend it, and just redefine process method – Takes an operational visitor as an argument
• Except for the few cases where something other than when created
preorder traversal is required
• Perform preorder traversal of structure
• Can define other traversal visitors as well – At each node
– E.g., PostOrderVisitor • Have node accept operational visitor
• Have each child accept traversal visitor

Design patterns, CMSC 433 47 Design patterns, CMSC 433 48

8
PreorderVisitor with payload Why patterns?
• Class PreorderVisitor { • Sometimes, patterns are just a cool idea you might
Visitor payload; not have come up with on your own
void visit(BinaryPlusOperatorNode n) { – Learn from others

payload->visit(n); • If you work with code written by someone else


– If they use a pattern you know, it will be easier for you
n->lhs->accept(this); to understand their code
n->rhs->accept(this);
• Some frameworks can automatically
} build/manipulate certain design patterns
…}

Design patterns, CMSC 433 49 Design patterns, CMSC 433 50

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++ have very different
solutions in Smalltalk or Dylan

Design patterns, CMSC 433 51

You might also like