Behavioral Pattern: Strategy C h a p t e r 5 – P a g e 205 The Open-Closed Principle advocates designing software in such a way that it will absorb new.

Slides:



Advertisements
Similar presentations
Behavioral Pattern: Visitor C h a p t e r 5 – P a g e 224 When an algorithm is separated from an object structure upon which it operates, new operations.
Advertisements

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use.
Behavioral Pattern: Template Method C h a p t e r 5 – P a g e 217 On occasion, two different components in a software system will have significant similarities,
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
Design Patterns Part II (TIC++V2:C10) Yingcai Xiao 10/01/08.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Spring 2010ACS-3913 Ron McFadyen1 Duck Example Consider the text example (up to page 6). Each type of duck is a subclass of Duck Most subclasses implement.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Behavioral Pattern: Memento C h a p t e r 5 – P a g e 179 Objects frequently expose only some of their internal state using public methods, but there.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Behavioral Patterns C h a p t e r 5 – P a g e 128 BehavioralPatterns Design patterns that identify and realize common interactions between objects Chain.
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
1 CSC241: Object Oriented Programming Lecture No 27.
Object Oriented Programming Key Features of OO Approach Data encapsulation –data and methods are contained in a single unit, object –promotes internal.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
1 GoF Template Method (pp ) GoF Strategy (pp ) PH Single User Protection (pp ) Presentation by Julie Betlach 6/08/2009.
Case Studies on Design Patterns Design Refinements Examples.
CS 325: Software Engineering March 17, 2015 Applying Patterns (Part A) The Façade Pattern The Adapter Pattern Interfaces & Implementations The Strategy.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Wage Calculator Application.
Behavioral Pattern: Command C h a p t e r 5 – P a g e 139 There are times when the need arises to issue a request to an object without knowing anything.
Behavioral Pattern: Observer C h a p t e r 5 – P a g e 186 A large monolithic design does not scale well as additional graphical and monitoring requirements.
CS 350 – Software Design The Strategy Pattern – Chapter 9 Changes to software, like other things in life, often focus on the immediate concerns and ignore.
Strategy Design Patterns CS 590L - Sushil Puradkar.
Computing IV Singleton Pattern Xinwen Fu.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2.
Structural Pattern: Bridge When the abstract interface and the concrete implementation have been set up as parallel class hierarchies, it becomes difficult.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
05/26/2004www.indyjug.net1 Indy Java User’s Group May Knowledge Services, Inc.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
C++ Classes and Data Structures Jeffrey S. Childs
Behavioral Pattern: Iterator C h a p t e r 5 – P a g e 159 Software can become difficult to manage when a variety of different traversals of a variety.
11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 9 Classes: A Deeper Look, Part I Part II.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Creational Pattern: Builder When a complex object needs to be created, it is sometimes beneficial to separate the construction of the object from its.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
The Strategy Design Pattern © Allan C. Milne v
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
CS 325: Software Engineering March 19, 2015 Applying Patterns (Part B) Code Smells The Decorator Pattern The Observer Pattern The Template Method Pattern.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Behavioral Pattern: Mediator C h a p t e r 5 – P a g e 169 When a program is made up of several classes, the logic and computation is divided among these.
PROTOTYPE. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory.
Structural Patterns C h a p t e r 4 – P a g e 55 StructuralPatterns Design patterns that describe how classes and objects can be combined to form larger.
Design Patterns Behavioral Patterns. Chain of Responsibility Avoid coupling the sender of a request to its receiver by giving more than one object a chance.
STRATEGY PATTERN By Michelle Johnson. BACKGROUND Behavioral Pattern Allow you to define a family of algorithms, encapsulate each one, and make them interchangeable.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Creational Patterns C h a p t e r 3 – P a g e 14 Creational Patterns Design patterns that deal with object creation mechanisms and class instantiation,
Strategy Design Pattern
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
CS 350 – Software Design The Strategy Pattern – Chapter 9
Creational Pattern: Prototype
Introduction to Classes
SE-2811 Software Component Design
DESIGN PATTERNS : Strategy Pattern
Design pattern Lecture 9.
Strategy Design Pattern
Design Patterns (Gamma, Helm, Johnson, Vlissides)
Exception Handling.
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

Behavioral Pattern: Strategy C h a p t e r 5 – P a g e 205 The Open-Closed Principle advocates designing software in such a way that it will absorb new variations without having to introduce new fundamental structure, enabling the capabilities of a system to be extended without substantially changing the basic system. The Strategy Pattern attempts to accomplish this by encapsulating each algorithm in a family of algorithms and making them all interchangeable, thus allowing each algorithm to vary independently of the clients that use it. This permits a program to switch easily between algorithms without resorting to monolithic if-else statements. This approach allows the behavior in question to be modified at run-time and not just at design time.

The Strategy Pattern C h a p t e r 5 – P a g e 206 The Strategy declares an interface common to all supported algorithms, using this interface to call the algorithm defined by a ConcreteStrategy. The ConcreteStrategy implements the algorithm using the Strategy interface. The Context is configured with a ConcreteStrategy object, maintains a reference to a Strategy object, and may define an interface that lets the Strategy object access its data.

C h a p t e r 5 – P a g e 207 Non-Software Example: Airport Transportation Modes of transportation to an airport is an example of a Strategy. Several options exist, such as driving one's own car, taking a taxi, an airport shuttle, or a limousine service. For some airports, subways and helicopters are also available as a mode of transportation to the airport. Any of these modes of transportation will get a traveler to the airport, and they can be used interchangeably. The traveler must chose the Strategy based on tradeoffs between cost, convenience, and time.

C h a p t e r 5 – P a g e 208 Software Example: Event Handler The NetworkManagement context needs strategies for handling various events on the network. The Connection strategy is to respond by indicating a need for greater bandwidth. The Path strategy is to respond by indicating a need for some alternative path through the network. The LSP strategy is to respond by indicating a need for an alternative path through the network that meets specific label switched path requirements. (Note that this model utilizes both the Strategy Pattern and the Chain of Responsibility Pattern.)

C h a p t e r 5 – P a g e 209 Event Handler Strategy C++ Code #include using namespace std; typedef int Event; const Event LINK_1_BROKEN = 1; const Event LINK_2_BROKEN = 2; const Event CONGESTION = 3; const Event No_Event_Support = -1; class EventHandler { public: explicit EventHandler(EventHandler* hdlr = 0, Event evt = No_Event_Support); virtual const bool HasEventSupport(Event evt); virtual void SetHandler(EventHandler* hdlr, Event evt); virtual void HandleEvent(Event evt); virtual ~EventHandler() { cout << "Now in the EventHandler destructor" << endl; }; private: EventHandler* successor; Event currentEvent; };

C h a p t e r 5 – P a g e 210 //Set up a chain of event handlers EventHandler::EventHandler( EventHandler* hdlr, Event evt ) : successor(hdlr), currentEvent(evt) { } const bool EventHandler::HasEventSupport(Event incomingEvent) { return currentEvent == incomingEvent; } void EventHandler::SetHandler(EventHandler* hdlr, Event evt) { successor = hdlr; currentEvent = evt; } void EventHandler::HandleEvent (Event incomingEvent) { if (incomingEvent != currentEvent) { if (successor != 0) { cout << "HandleEvent () calling into successor" << endl; successor->HandleEvent(incomingEvent); } else { cout << "Base class help now follows" << endl; }

C h a p t e r 5 – P a g e 211 class Connection : public EventHandler { public: Connection(Event evt) : EventHandler(0, evt) { } virtual void HandleEvent(Event incomingEvent); }; void Connection::HandleEvent(Event incomingEvent) { if (HasEventSupport(incomingEvent)) { // Offer event support cout << "Here's some Connection Event support" << endl; cout << "You may need additional bandwidth" << endl << endl; } else { cout << "No support from Connection - Sorry!" << endl; cout << "Calling the base class event handler" << endl; EventHandler::HandleEvent(incomingEvent); }

C h a p t e r 5 – P a g e 212 class Path : public Connection { public: Path::Path(Connection* conx, Event evt) : Connection(0) { cout << "In the Path constructor" << endl; SetHandler(conx, evt); } void HandleEvent(Event incomingEvent) { if (HasEventSupport(incomingEvent)) { // Offer event support cout << "Here's some Path Event support" << endl; cout << "We need a new path" << endl << endl; } else { cout << "No support from Path - Sorry!" << endl; cout << "Calling the base class event handler" << endl; EventHandler::HandleEvent(incomingEvent); } };

C h a p t e r 5 – P a g e 213 class Lsp : public Connection { public: Lsp::Lsp(string lspID, Connection* conx, Event evt) : Connection(0) { cout << "Constructing Lsp: " << lspID << endl; lspName = lspID; SetHandler(conx, evt); } void HandleEvent(Event incomingEvent) { if (HasEventSupport(incomingEvent)) { // Offer event support cout << "At last, here's some LSP Event support:" << endl; cout << "We need an alternative path for " << lspName << endl << endl; } else EventHandler::HandleEvent(incomingEvent); } private: string lspName; };

C h a p t e r 5 – P a g e 214 void main() { // Set up a Path->LSP->Connection Chain of Responsibility Connection* connection = new Connection(CONGESTION); Lsp* lsp = new Lsp("LSP123", connection, LINK_1_BROKEN); Path* path = new Path(lsp, LINK_2_BROKEN); cout << endl << "Time to handle network events" << endl << endl; //A network event has occurred, e.g., CONGESTION //Let's see who can handle this event cout << "Let's simulate a network error: CONGESTION" << endl; path->HandleEvent(CONGESTION); //Another network event has occurred, e.g., LINK_1_BROKEN //Let's see who can handle this event cout << "Let's simulate another network error: LINK_1_BROKEN" << endl; path->HandleEvent(LINK_1_BROKEN); cout << "Let's simulate one more network error: LINK_2_BROKEN" << endl; path->HandleEvent(LINK_2_BROKEN); delete path; delete lsp; delete connection; }

C h a p t e r 5 – P a g e 215

Strategy Pattern Advantages C h a p t e r 5 – P a g e 216 With the Strategy Pattern, a family of algorithms can be defined as a class hierarchy and can be used interchangeably to alter an application’s behavior without changing its architecture. By encapsulating the algorithm separately, new algorithms complying with the same interface can easily be introduced. The application can switch strategies at run-time, and clients can choose the required algorithm without using a “switch” statement or a series of “if-else” statements. Data structures used for implementing the algorithm are completely encapsulated in Strategy classes, so the implementation of an algorithm can be changed without affecting the Context class.