oo design patterns
TRANSCRIPT
-
7/31/2019 OO Design Patterns
1/49
OO Design Patterns
CSI323 Lecture
-
7/31/2019 OO Design Patterns
2/49
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
-
7/31/2019 OO Design Patterns
3/49
-
7/31/2019 OO Design Patterns
4/49
What is a Design Pattern?
A pattern is a named problem/solution pair that can beapplied in new contexts, with advice on how to apply it innovel situations.
Patterns provide guidance for how responsibilities should beassigned to objects, given a specific category of problem.
Patterns typically do not contain new ideas. Patterns
attempts to codify existing knowledge, idioms and principles.
-
7/31/2019 OO Design Patterns
5/49
What is a Design Pattern? (contd)
There are four essential elements of a pattern.
Pattern name Problem describes when to apply the pattern. Solution describes the elements that make up the design. Consequences are the results and trade-offs of applying the
pattern.
Usually descriptions of communicating objects and classes thatare customized to solve a general design problem in aparticular context.
-
7/31/2019 OO Design Patterns
6/49
-
7/31/2019 OO Design Patterns
7/49
-
7/31/2019 OO Design Patterns
8/49
-
7/31/2019 OO Design Patterns
9/49
-
7/31/2019 OO Design Patterns
10/49
-
7/31/2019 OO Design Patterns
11/49
Creator
:Catalog :Book1 : create(title)
makeBook(title)
by Creator
-
7/31/2019 OO Design Patterns
12/49
-
7/31/2019 OO Design Patterns
13/49
Controller - Facades
Facades are covers. Intent a class that (in some way) represents an overall cover.
:LibraryborrowResource(callNum)
by Controller
-
7/31/2019 OO Design Patterns
14/49
Controller Facades (contd)
Other facades? a class representing the system, e.g., The software information system. The device that includes a computer and software (e.g., ATM) Etc.
:LibraryborrowResource(callNum)
:LibInfoSystemborrowResource(callNum)
-
7/31/2019 OO Design Patterns
15/49
Observer design patterns Behavioral Pattern one-to-many dependency model, so that when one object
changes state, all its dependents are notified and updatedautomatically without coupling the notifying object to the
objects that are notified.
Example: Button expose a clicked event that encapsulate click state,
thus publish himself as an observable. Clients that areinterested in this event register to it, thus becomes observers. Observer and observable are bonded in a contract and can be
completely loosely coupled from one another.
-
7/31/2019 OO Design Patterns
16/49
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;}
}
-
7/31/2019 OO Design Patterns
17/49
Factory design patterns(abstract\method\Lightweight)
Creational pattern Can be given to client (abstract), pass
construction parameters or read creationtypes from configuration or systemenvironment
Can use object pool (Lightweight)
-
7/31/2019 OO Design Patterns
18/49
-
7/31/2019 OO Design Patterns
19/49
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();
}
}
Factory design pattern - example
-
7/31/2019 OO Design Patterns
20/49
Faade design pattern
Structural Pattern Provide a unified interface to a set of interfaces in a
subsystem without damaging the genric form of the
sub system.
-
7/31/2019 OO Design Patterns
21/49
-
7/31/2019 OO Design Patterns
22/49
Strategy design pattern
Behavioral Pattern defines a family of interchangeable encapsulated algorithms that receivesthe same input type and provides the same output type in differentmanners that can be determined in run-time.
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();
}
-
7/31/2019 OO Design Patterns
23/49
Strategy design pattern - example
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}
}
-
7/31/2019 OO Design Patterns
24/49
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);}
}
Strategy design pattern - example
-
7/31/2019 OO Design Patterns
25/49
Consumer/Producer
Concurrency Pattern This design pattern coordinates the
concurrent production and consumption of information among producer and consumerobjects that are working on different threads.
This pattern is used with some type of semaphore
-
7/31/2019 OO Design Patterns
26/49
Consumer/Producer - examplestatic AutoResetEvent eventProducerDone = new AutoResetEvent(false);static AutoResetEvent eventConsumerDone = new AutoResetEvent(false);static int currentNum = 0;
static void produce(object stateInfo){
eventProducerDone.Set();while (true){
//wait for the consumereventConsumerDone.WaitOne();
currentNum++;eventProducerDone.Set();
}}
-
7/31/2019 OO Design Patterns
27/49
static void Main(string[] args){
ThreadPool.QueueUserWorkItem(newWaitCallback(produce));
for (int i = 0; i < 20; i++){
eventProducerDone.WaitOne();System.Diagnostics.Debug.WriteLine(currentNum);eventConsumerDone.Set();
}}
Consumer/Producer - example
-
7/31/2019 OO Design Patterns
28/49
Model View Controller The Model-View-Controller (MVC) pattern
separates the modeling of the domain, thepresentation, and the actions based on userinput into three separate classes
The controller changes the model The View Listens to Model
Changed events and
update itself Recursive MVC
-
7/31/2019 OO Design Patterns
29/49
Subject-observer
[from Vlissides]
-
7/31/2019 OO Design Patterns
30/49
Subject-observer (cont.)
Subject
Register(Observer)Unregister(Observer)
NotifyAll()
Observer
OnUpdate()
1 *
for all o in observers {
o.OnUpdate()}
-
7/31/2019 OO Design Patterns
31/49
Subject-observer (cont.)
Subject
Register(Observer)Unregister(Observer)
NotifyAll()
Observer
virtual OnUpdate()
1 *
for all o in observers {o.OnUpdate()}
ConcreteSubject ConcreteObserver
virtual OnUpdate()
-
7/31/2019 OO Design Patterns
32/49
-
7/31/2019 OO Design Patterns
33/49
MVC (cont.)
Subject
Register(Observer)Unregister(Observer)
NotifyAll()
Observer
virtual OnUpdate()
1 *
for all o in observers {o.OnUpdate()}
Controller View
virtual OnUpdate()
-
7/31/2019 OO Design Patterns
34/49
MVC (cont.)
class Observer{
protected:virtual void OnUpdate(MsgId message_id) = 0;
};
class Subject{
public:enum MsgId {};void RegisterObserver(Observer* obs);virtual void NotifyAllObservers(MsgId message_id) {
for (int i=0 ; iOnUpdate(message_id);
}}
private:std::vector m_observers;
};
-
7/31/2019 OO Design Patterns
35/49
MVC (cont.)
class Controller : public Subject{
Controller(Data* d) : m_data(d) {}const Data* GetData() const;
void AddSphere(const Sphere& s) { m_data->AddSphere(s); NotifyAllObservers(ADD_SPHERE);
} private:
Data* m_data;};
-
7/31/2019 OO Design Patterns
36/49
MVC (cont.)
class MainWnd : public Observer{
public: MainWnd(Controller* c) : m_controller(c) {
c.Register(this);
}virtual void OnUpdate(int message_id) {
switch (message_id) {case Subject::ADD_SPHERE:
...}
} private:
Controller* m_controller;};
-
7/31/2019 OO Design Patterns
37/49
Adapter You have
legacy code current client
Adapter changes interface of legacy code so clientcan use it
Adapter fills the gap b/w two interfaces No changes needed for either
legacy code, or client
-
7/31/2019 OO Design Patterns
38/49
Adapter (cont.)
class NewTime{
public:int GetTime() {
return m_oldtime.get_time() * 1000 + 8;}
private:OldTime m_oldtime;
};
-
7/31/2019 OO Design Patterns
39/49
Command
You have commands that need to be executed, undone, or queued
Command design pattern separates Receiver from Invoker from Commands
All commands derive from Command andimplement do(), undo(), and redo()
-
7/31/2019 OO Design Patterns
40/49
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
-
7/31/2019 OO Design Patterns
41/49
Composite
You want uniformly to treat items (atomic elements), and groups (containing items or other groups)
Composite interface specifies operations thatare shared between items and groups
Examples: hierarchy of files and directories,
groups of drawable elements
-
7/31/2019 OO Design Patterns
42/49
Composite (cont.)
GroupItem
Composite
-
7/31/2019 OO Design Patterns
43/49
Proxy
You want to delay expensive computations, use memory only when needed, or
check access before loading an object into memory Proxy
has same interface as Real object stores subset of attributes does lazy evaluation
-
7/31/2019 OO Design Patterns
44/49
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
-
7/31/2019 OO Design Patterns
45/49
Strategy (cont.)
Client
Strategy
Concrete
StrategyA
Concrete
StrategyB
Context
Policy
-
7/31/2019 OO Design Patterns
46/49
Bridge
You have several different implementations need to choose one, possibly at run time
Bridge decouples interface from implementation shields client from implementations Abstraction creates and initializes the
ConcreteImplementations Example: stub code, slow code, optimized code
-
7/31/2019 OO Design Patterns
47/49
Bridge (cont.)
Client
Implementor
Refined Abstraction
ConcreteImplementorA
ConcreteImplementorB
Abstraction
-
7/31/2019 OO Design Patterns
48/49
Design pattern space
[from Vlissides]
-
7/31/2019 OO Design Patterns
49/49
END