The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming Basics Prof. Ankur Teredesai, Computer Science Department, RIT.
Advertisements

CS 350 – Software Design The Bridge Pattern – Chapter 10 Most powerful pattern so far. Gang of Four Definition: Decouple an abstraction from its implementation.
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.
Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Inheritance issues SE-2811 Dr. Mark L. Hornick 1.
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 Design Patterns: someone has already.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
Chapter 1: Introduction to Design Patterns. SimUDuck Example.
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.
SE2811 Week 7, Class 1 Composite Pattern Applications Conceptual form Class structure Coding Example Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance in the Java programming language J. W. Rider.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Week 2, Day 2: The Factory Method Pattern Other good design principles Cohesion vs. Coupling Implementing the Strategy Pattern Changing strategies (behaviors)
Week 6, Class 1 & 2: Decorators Return Exam Questions about lab due tomorrow in class? Threads Locking on null object invokeLater & the squares example.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
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.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
CS 210 Introduction to Design Patterns August 29, 2006.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
The Strategy Design Pattern © Allan C. Milne v
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
Systems Requirements SE 3821 Design? Algorithms CS 2852.
SE-2811 Software Component Design Week 1, Day 2 Making teams Warm-up exercise Design pattern defined SE-2811 Dr. Josiah Yoder Slide style: Dr. Hornick.
Systems Requirements SE 3821 Design? Algorithms CS 2852.
Week 5, Day 2: Decorator Decorators Muddiest Point Tomorrow: Quiz on lab reading: web.msoe.edu/hasker/se2811/labs/5/ SE-2811 Slide design:
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Slide design: Dr. Mark L. Hornick
// create some behaviors SwimBehavior csb = new CircularSwimming(); QuackBehavior sqb = new StandardQuacking(); SwimBehavior rsb = new RandomFloating();
STRATEGY PATTERN By Michelle Johnson. BACKGROUND Behavioral Pattern Allow you to define a family of algorithms, encapsulate each one, and make them interchangeable.
SE-2811 Software Component Design Week 1, Day 1 Design pattern defined Code that needs a design pattern… SE-2811 Dr. Josiah Yoder Slide style: Dr. Hornick.
Week 5, Class 3: Decorators Lab questions? Example: Starbuzz coffee Basic Pattern More examples Design Principles Compare with alternatives SE-2811 Slide.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
The Decorator Pattern Decorators in Java I/O classes SE-2811 Dr. Mark L. Hornick 1.
SE 461 Software Patterns Welcome to Design Patterns.
OOP: Encapsulation &Abstraction
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Strategy Pattern.
Object-Oriented Programming Basics
Week 2, Day 1: The Factory Method Pattern
Behavioral Design Patterns
Strategy Design Pattern
SE-2811 Software Component Design
Object Oriented Analysis and Design
SE-2811 Software Component Design
SE-2811 Software Component Design
Interfaces.
SE-2811 Software Component Design
14. Factory Pattern SE2811 Software Component Design
SE-2811 Software Component Design
14. Factory Pattern SE2811 Software Component Design
Design Patterns (Gamma, Helm, Johnson, Vlissides)
Object-Oriented PHP (1)
Slide design: Dr. Mark L. Hornick
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2

Review What problems are we trying to avoid? What do we want to achieve? SE-2811 Dr. Mark L. Hornick 2

A different approach: Isolate behaviors that vary, and encapsulate them as attributes to eliminate implementation inheritance and class explosions: SE-2811 Dr. Mark L. Hornick 3 SimUDuck v5

Sorting Example Suppose we have a program that sorts Class objects Perhaps alphabetically, perhaps by “closeness of fit” Perhaps using Bubble Sort, or a (much better) algorithm like Merge Sort. SE-2811 Dr. Mark L. Hornick 4

Consider Collections.sort() Collections.sort() implements an argument which is a reference to a concrete class that implements the Comparator interface, and thus the behavior of the compare() method. Depending on the strategy of the compare() method in the concrete class, different sorting will be used by Collections.sort(). The comparison strategy is decoupled from the Collections.sort() method itself. SE-2811 Dr. Mark L. Hornick 5

Another sorting example Different strategies for sorting MergeSort O(NlogN) QuickSort O(NlogN) ShellSort In-place, Ω(N(logN/log logN) 2 ) InsertionSort O(N 2 ) BubbleSort O(N 2 ) Cool sorting algorithms of the future (or past) … Would be nice to “plug in” new strategies SE-2811 Dr. Josiah Yoder Idea: 6

The Strategy Design Pattern in its general form: ConcreteStrategy classes implement specific behaviors The Context is the class that encapsulates and uses a specific behavior, or Strategy. A Strategy is an interface that defines a behavior

Applying the Strategy Pattern: Evidence 1 The Strategy Pattern is a behavioral pattern usually considered and applied at design-time. Premise: Your application requires similar objects whose behavior varies. SE-2811 Dr. Mark L. Hornick 8

Applying the Strategy Pattern: Evidence 2 As a designer, you watch for inheritance patterns that result in excessive behavior overrides and/or code duplication among classes. SE-2811 Dr. Mark L. Hornick 9

Applying the Strategy Pattern: Action! Leave behavior that is truly shared in abstract classes. Isolate behavior(s) that vary and declare interfaces that define those behaviors Implement the behaviors in separate concrete classes whose references can be passed to the Duck ctor SE-2811 Dr. Mark L. Hornick 10

Creating Ducks with specific behaviors // create some behaviors SwimBehavior csb = new CircularSwimming(); QuackBehavior sqb = new StandardQuacking(); SwimBehavior rsb = new RandomFloating(); // daffy has circular swimming, std quacking Waterfowl daffy = new Duck(“daffy”, csb, sqb); // donald has random floating, std quacking Waterfowl donald = new Duck(“donald”, rsb, sqb); daffy.swim(); donald.quack(); SE-2811 Dr. Mark L. Hornick 11

Inside a Duck class // constructor public void Duck(String name, SwimBehavior sb, QuackBehavior qb) { super(name, sb, qb) } SE-2811 Dr. Mark L. Hornick 12

Inside a Waterfowl class public abstract class Waterfowl { private SwimBehavior swimBehavior; private QuackBehavior quackBehavior; private String name; // constructor public void Waterfowl(String name, SwimBehavior sb, QuackBehavior qb) { this.name = name; swimBehavior = sb; quackBehavior = qb; } // centralize implementation of behaviors in top-level classes // if possible; avoid duplication of behavior in subclasses. // Note we can make this method final to prevent subclasses from overriding it! public void swim() { swimBehavior.swim(); // invoke the specific behavior }... SE-2811 Dr. Mark L. Hornick 13

Strategy is a Behavioral Design Pattern The Strategy pattern allows for selection of specific behavioral algorithms at runtime, since the selected strategy is just an attribute of the class using the Strategy. We can select particular behavioral strategies when we constructed the Ducks But since the swim() or quack() behaviors of Duck are just attributes (references) to concrete Strategy classes, we could easily change the behaviors at any time with a simple setSwimBehavior() mutator method!

The Strategy pattern favors Encapsulation over Extension That is, rather than changing the behavior implemented within a derived class by extending from a parent/base class, we encapsulate behaviors into a class as instance attributes, which can be varied. The Strategy pattern lets us vary and change behavioral algorithms independently of the clients that use the behaviors.

A good Design Pattern has also solved a larger conceptual issue: To make a program easy to maintain, we always want to strive for 1. High cohesion 2. Low coupling SE-2811 Dr. Mark L. Hornick 16

Coupling: How closely two or more classes are related Does changing code in one class require changes in another class?? If “yes”, then it has high coupling (bad) Changing swim or quack behaviors does not require changes to the Duck class (low coupling) Cohesion (?) -- Grouping similar functionality in a single place in the code -- Few behavior in a class -- Each class should have one focus SE-2811 Dr. Mark L. Hornick 17

Other design principles benefitting from the Strategy Pattern Decreases coupling, increases cohesion The behavior of the Duck is not coupled to the Duck – behaviors are implemented separately. Like all Design Patterns, the Strategy pattern allows us to vary a part of the system (swim and quack behavior) independently of other parts

Other good design principles we visited Code to the highest level of abstraction that is possible in a given context: i. ArrayList = new ArrayList // bad ii. List = new ArrayList // good iii. Collection = new ArrayList // better

Other good design principles we visited Code to most restrictive level of access modification that is possible in a given context: i. Use public for constants and methods; never for attributes. On methods: only on those you want to support for public consumption ii. Use /*package*/ if cooperating classes in the same package need access to attributes or special methods iii. Use protected to allow derived classes in any package access to members iv. Use private to completely guard members from view outside the defining class

Are there disadvantages? Yes: the implementation of the Strategy Pattern is somewhat more complicated than using inheritance All design patterns usually exhibit this type of tradeoff. SE-2811 Dr. Mark L. Hornick 21