CS754 - 6 Design Patterns
CS754 - 6 Design Patterns
CS754 - 6 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
• 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
6
Solution
• Describes the elements that make up the
– design
– relationships
– responsibilities
– collaborations
7
Consequences
• Results and trade-offs of applying the pattern
• Critical for:
– evaluating design alternatives
– understanding costs
– understanding benefits of applying the pattern
• 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
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
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
} +detach(in Observer)
ConcreteObserver
ConcreteSubject
-subjectSate * +update()
1
+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;
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
25
Façade…
26
Façade… Consequences
• Shields clients from subsystem components,
making the subsystem easier to use
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
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()
36
Subject-observer…
1 *
Subject Observer
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);
}