CS754 - 6 Design Patterns

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Design Patterns

1
What is a Design Pattern?

• A design pattern
– abstracts a recurring design structure
– comprises class and/or object
• dependencies,
• structures,
• interactions, or
• conventions
– distills design experience

2
Re-use
• Code re-use
– Don’t reinvent the wheel
– Requires clean, elegant, understandable, general, stable
code
– leverage previous work
• Design re-use
– Don’t reinvent the wheel
– Requires a precise understanding of common, recurring
designs
– leverage previous work

3
Elements of Design Patterns
• Design patterns have four essential elements:
– Pattern name

– Problem

– Solution

– Consequences

4
Pattern Name
• Used to describe:
– a design problem
– its solutions

• Increases design vocabulary

• Makes it possible to design at a higher level of


abstraction

• Enhances communication
• “The Hardest part of programming is coming up with
good variable [function, and type] names.”
5
Problem
• Describes when to apply the pattern

• Explains the problem and its context

• May describe specific design problems and/or


object structures

• May contain a list of preconditions that must be


met before it makes sense to apply the pattern

6
Solution
• Describes the elements that make up the
– design
– relationships
– responsibilities
– collaborations

• Does not describe specific concrete


implementation

• Abstract description of design problems and how


the pattern solves it

7
Consequences
• Results and trade-offs of applying the pattern

• Critical for:
– evaluating design alternatives
– understanding costs
– understanding benefits of applying the pattern

• Includes the impacts of a pattern on a system’s:


– flexibility
– extensibility
– portability
8
Design Patterns are NOT
• Designs that can be encoded in classes and reused as
is (i.e., linked lists, hash tables)

• Complex domain-specific designs (for an entire


application or subsystem)

• They are:
– “Descriptions of communicating objects and classes that
are customized to solve a general design problem in a
particular context.”

9
Describing Design Patterns
• Graphical notation is generally not sufficient

• In order to reuse design decisions the alternatives


and trade-offs that led to the decisions are critical
knowledge

• Concrete examples are also important

• The history of the why, when, and how set the


stage for the context of usage

10
Describing Design Patterns
• Name and Classification: Essence of pattern
• Intent: What it does, its rationale, its context
• AKA: Other well-known names
• Motivation: Scenario illustrates a design problem
• Applicability: Situations where pattern can be applied
• Structure: Class and interaction diagrams
• Participants: Objects/classes and their responsibilities
• Collaborations: How participants collaborate
• Consequences: Trade-offs and results
• Implementation: Pitfalls, hints, techniques, etc.
• Sample Code
• Known Uses: Examples of pattern in real systems
• Related Patterns: Closely related patterns
11
Example: Stock Quote Service
Real time
Market
Data
Feed

Stock Quotes

Customer Customer

Customer Customer Customer


Observers

12
Observer Pattern
• Intent:
– Define a one-to-many dependency between objects so
that when one object changes state, all its dependents are
notified and updated automatically
• Key forces:
– There may be many observers
– Each observer may react differently to the same
notification
– The subject should be as decoupled as possible from the
observers to allow observers to change independently of
the subject

13
Structure of Observer Pattern
Subject Observer

for all observers obs +notify() * +update()


{
obs->update()
+attach(in Observer) 1

} +detach(in Observer)

ConcreteObserver
ConcreteSubject
-subjectSate * +update()
1
+getState()

return subjectState observerState = subject->getState()

14
Collaborations in Observer Pattern

15
Types of Patterns
• Creational patterns:
– Deal with initializing and configuring classes and objects

• Structural patterns:
– Forming larger structures by composition – inheritance
– Composition of classes or objects

• Behavioural patterns:
– Deal with dynamic interactions among societies of classes
and objects
– How they distribute responsibility

16
Design Pattern Space
Purpose
Creational Structural Behavioral
Scope Class Factory method Adapter (class) Interpreter
Template method
Object Abstract factory Adapter (object) Chain of
Builder Bridge responsibility
Prototype Composite Command
Singleton Decorator Iterator
Façade Mediator
Flyweight Memento
Proxy Observer
State
Strategy
Visitor
CREATIONAL

Design Patterns

18
Singleton design pattern
• Creational pattern
• ensure that a class has only one instance, and to provide a global point of
access to it

Example:
Class SomeClass
{
static SomeClass singleTonInstance = null;

static SomeClass GetInstance()


{
if(singleTonInstance == null)
singleTonInstance = new SomeClass()
return singleTonInstance;
}
}
19
Factory design patterns
(abstract\method\Lightweight)
• Creational pattern
• Can be given to client (abstract), pass construction
parameters or read creation types from configuration
or system environment
• Can use object pool (Lightweight)

20
Factory design pattern - example
abstract class GUIFactory {
public static GUIFactory getFactory() {
int sys = readFromConfigFile("OS_TYPE");
return sys == 0 ? new WinFactory() : new MacFactory();
}
public abstract Button createButton();
}
class WinFactory:GUIFactory {
public override Button createButton() {
return new WinButton();
}
}
class MacFactory:GUIFactory {
public override Button createButton(){
return new MacButton();
}
}
abstract class Button {
public string caption;
public abstract void paint();
}
21
Factory design pattern - example
class WinButton:Button
{
public override void paint()
{ // paint a button with Win API…}
}
class MacButton:Button
{
public override void paint()
{ // paint a button Mac style… }
}
class Application
{
static void Main(string[] args)
{
GUIFactory aFactory = GUIFactory.getFactory();
Button aButton = aFactory.createButton();
aButton.caption = "Play"; aButton.paint();
}
} 22
STRUCTURAL

Design Patterns

23
Facade
• You
– have a set of related classes
– want to shield the rest of the system from these
details

• Facade provides a simplified interface


• Encapsulates a subsystem
• Defines interface to a layer
24
Façade…
• Structural Pattern
• Provide a unified interface to a set of interfaces in a
subsystem without damaging the genric form of the
sub system.

25
Façade…

26
Façade… Consequences
• Shields clients from subsystem components,
making the subsystem easier to use

• Promotes weak coupling between subsystems

• Leads to reducing compilation dependencies

• Doesn’t prevent clients from directly accessing


subsystem components

27
Façade…
• combine a parser, lexical analyzer, and other
tools into a subsystem with a common
interface

28
Adapter
• You have
– legacy code
– current client

• Adapter changes interface of legacy code so client can


use it

• Adapter fills the gap b/w two interfaces

• No changes needed for either


– legacy code, or
– client

29
Adapter …
class NewTime
{
public:
int GetTime() {
return m_oldtime.get_time() * 1000 + 8;
}
private:
OldTime m_oldtime;
};

30
Adapter …
• Interchangeable hardware problem
• A company makes a system that includes a camera. The
system has to support many brands of cameras
• All cameras respond to the same kinds of commands,
but the exact interfaces will vary.
• The system will be configured by the customer at
delivery by choosing the camera they are using
• New cameras are released frequently
• We have to be able to easily upgrade our customers
31
Adapter …

32
Adapter…

33
BEHAVIORAL

Design Patterns

34
Subject-observer

[from Vlissides]
35
Subject-observer…

1 * Observer
Subject

Register(Observer) OnUpdate()
Unregister(Observer)
NotifyAll()

for all o in observers {


o.OnUpdate()
}

36
Subject-observer…
1 *
Subject Observer

Register(Observer) virtual OnUpdate()


Unregister(Observer)
NotifyAll() for all o in observers {
o.OnUpdate()
}

ConcreteSubject ConcreteObserver

virtual OnUpdate()

37
Strategy
• You want to
– use different algorithms depending upon the context
– avoid having to change the context or client

• Strategy
– decouples interface from implementation
– shields client from implementations
– Context is not aware which strategy is being used;
Client configures the Context
– strategies can be substituted at runtime
– example: interface to wired and wireless networks
38
Strategy …

Client Policy

Context Strategy

Concrete Concrete
StrategyA StrategyB

39
Strategy …
static void Main(
{
SortedList studentRecords = new SortedList();
studentRecords.Add("Samual");
studentRecords.Add("Jimmy");
studentRecords.Add("Sandra");
studentRecords.SetSortStrategy(new QuickSort());
studentRecords.Sort();
studentRecords.SetSortStrategy(new ShellSort());
studentRecords.Sort();
}

40
Strategy …
abstract class SortStrategy
{
public abstract void Sort(ArrayList list)
}
class QuickSort : SortStrategy
{
public override void Sort(ArrayList list)
{
list.Sort(); // Default is Quicksort
}
}
class ShellSort : SortStrategy
{
public override void Sort(ArrayList list)
{
//list.ShellSort(); not-implemented
}
}
41
Strategy …
class SortedList
{
private ArrayList list = new ArrayList();
private SortStrategy sortstrategy;
public void SetSortStrategy(SortStrategy sortstrategy)
{
this.sortstrategy = sortstrategy;
}
public void Add(string name)
{
list.Add(name);
}

public void Sort()


{
sortstrategy.Sort(list);
}
}
42

You might also like