Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use.

Slides:



Advertisements
Similar presentations
The Singleton Pattern II Recursive Linked Structures.
Advertisements

Winter 2007ACS-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.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Design Patterns A General reusable solution to a commonly occurring problem in software design. Creational: Deal with object creation mechanisms – Example:
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
1 (More) Pattern Games CS : Software Design Winter /T10.
Design Patterns I 1. Creational Pattern Singleton: intent and structure Ensure a class has one instance, and provide a global point of access to it 2.
Design Patterns Based on Design Patterns. Elements of Reusable Object-Oriented Software. by E.Gamma, R. Helm, R. Johnson,J. Vlissides.
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.
Variable Scope Brackets, brackets…. brackets. Variable Scope /** * HelloWorld --- program that prints something to the screen. Blanca Polo */
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
1 GoF Template Method (pp ) GoF Strategy (pp ) PH Single User Protection (pp ) Presentation by Julie Betlach 6/08/2009.
Emeka Egbuonye CSPP March 02,2010 The Mediator Pattern.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Decorator, Strategy, State Patterns.
Strategy Design Patterns CS 590L - Sushil Puradkar.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
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.
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.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Design Patterns Yonglei Tao. Design Patterns  A design pattern describes a recurring design problem, a solution, and the context in which that solution.
SE-2811 Software Component Design Week 1, Day 2 (and 1-3 and 2-1) SE-2811 Dr. Josiah Yoder Slide style: Dr. Hornick 1.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
STRATEGY PATTERN. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
The Strategy Design Pattern © Allan C. Milne v
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Pattern Bridge. Definition Bridge is the structural pattern that separates abstraction from the implementation so that both of them can be changed independently.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Interfaces and Polymorphism CS 162 (Summer 2009).
Stéphane Ducasse 1 Strategy.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
PROTOTYPE. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory.
STRATEGY PATTERN By Michelle Johnson. BACKGROUND Behavioral Pattern Allow you to define a family of algorithms, encapsulate each one, and make them interchangeable.
CS 350 – Software Design The Decorator Pattern – Chapter 17 In this chapter we expand our e-commerce case study and learn how to use the Decorator Pattern.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
Exercise 1 Review OOP tirgul No Outline Polymorphism Exceptions A design example Summary.
Interfaces CMSC 202. Public Interfaces Objects define their interaction with the outside world through the their public interface. A class' public interface.
Design Patterns: Brief Examples
Strategy Design Pattern
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Factory Patterns 1.
Strategy Design Pattern
Operators Laboratory /11/16.
State Design Pattern 1.
Interfaces and Constructors
SE-2811 Software Component Design
DESIGN PATTERNS : Strategy Pattern
DESIGN PATTERNS : State Pattern
Design pattern Lecture 9.
Strategy Design Pattern
Design Patterns (Gamma, Helm, Johnson, Vlissides)
Exception Handling Contents
Exceptions and Exception Handling
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

 In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern.  In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

 The classes and/or objects participating in this pattern are:  Strategy (SortStrategy) ◦ declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy  ConcreteStrategy (QuickSort, ShellSort, MergeSort) ◦ implements the algorithm using the Strategy interface  Context (SortedList) ◦ is configured with a ConcreteStrategy object ◦ maintains a reference to a Strategy object ◦ may define an interface that lets Strategy access its data.

 Many algorithms exist for breaking a stream of text into lines. Hard-wiring all such algorithms into the classes that require them isn't desirable for several reasons: ◦ Clients that need linebreaking get more complex if they include the linebreaking code. That makes clients bigger and harder to maintain, especially if they support multiple linebreaking algorithms. ◦ Different algorithms will be appropriate at different times. We don't want to support multiple linebreaking algorithms if we don't use them all. ◦ It's difficult to add new algorithms and vary existing ones when linebreaking is an integral part of a client.  We can avoid these problems by defining classes that encapsulate different linebreaking algorithms.  An algorithm that's encapsulated in this way is called a strategy.

Initialize(); While (!done()) { //main loop Idle(); //do something useful } Cleanup(); public class ftocraw { public static void main(String[] args) throws Exception { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); boolean done = false; while (!done) { String fahrString = br.readLine(); if (fahrString == null || fahrString.length() == 0) done = true; else { double fahr = Double.parseDouble(fahrString); double celcius = 5.0/9.0*(fahr-32); System.out.println("F=" + fahr + ", C=" + celcius); } } System.out.println("ftoc exit"); }  Consider following main-loop structure  Ftocraw.java is a example program

 We place the generic application algorithm into a concrete class named ApplicationRunner > Application +init +idle +cleanup +done : boolean focStrategy ApplicationR unner +run public class ApplicationRunner { private Application itsApplication = null; public ApplicationRunner(Application app){ itsApplication = app; } public void run() { itsApplication.init(); while (!itsApplication.done()) itsApplication.idle(); itsApplication.cleanup(); } public interface Application { public void init(); public void idle(); public void cleanup(); public boolean done(); }

public class ftocStrategy implements Application { private InputStreamReader isr; private BufferedReader br; private boolean isDone = false; public static void main(String[] args) throws Exception { (new ApplicationRunner(new ftocStrategy())).run(); } public void init() { isr = new InputStreamReader(System.in); br = new BufferedReader(isr); } public void idle() { String fahrString = readLineAndReturnNullIfError(); if (fahrString == null || fahrString.length() == 0) isDone = true; else { double fahr = Double.parseDouble(fahrString); double celcius = 5.0/9.0*(fahr-32); System.out.println("F=" + fahr + ", C=" + celcius); } } public void cleanup() {System.out.println("ftoc exit"); } public boolean done() { return isDone; } private String readLineAndReturnNullIfError() { String s; try {s = br.readLine(); } catch(IOException e) { s = null; } return s; }

 Intent  Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.  Structure

 A Strategy defines a set of algorithms that can be used interchangeably.  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, a city bus, 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 tlme.

In this inflexible example, all the NumberCruncher code is in one big class… Why is this bad? Strategy is similar to Bridge; same basic structure; very different intent. The Strategy pattern is also similar to State, which allows a class to be configured with different behaviors from which it can select whenever it makes an interesting state transition.

What if there were not a CrunchAlgorithm interface… suppose instead that NumberCruncher had two subclasses, CorrectButSlowNumberCruncher, and FastButSloppyNumberCruncher…? Why is this bad?

Here’s another “correct” design... But there can be no polymorphism in the chooseAlgorithm() or implCode() methods, leading to maintenance difficulties. Adding a NewAndImprovedCrunch would require adding if-then-else logic everywhere that the different Crunches are used. If the Strategy pattern were applied instead, the only place where the concrete CrunchImpls would get referred to specifically is the one place that they get instantiated.

Intent: Allows multiple implementation strategies to be interchangeable, so that they can easily be swapped at run-time, and so that new strategies can be easily added. In this example, notice that client’s of NumberCruncher do not know about the different crunch algorithms. The NumberCruncher.crunch() method is free to decide which CrunchImpl to use at any time; new algorithms can be easily added.

Applicability of Strategy Pattern 1) Many related classes differ only in their behavior. Strategy allows to configure a single class with one of many behaviors 2) Different variants of an algorithm are needed that trade-off space against time. All these variants can be implemented as a class hierarchy of algorithms