Strategy Pattern1 Design Patterns 1.Strategy Pattern How to design for flexibility?

Slides:



Advertisements
Similar presentations
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.
Advertisements

+ Informatics 122 Software Design II Lecture 7 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
SE2811 Week 7, Class 2 The Gang of Four and more … Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder.
D ESIGN P ATTERNS Introduction. C OURSE D ESCRIPTION Traditionally, OO designers have developed their own private "catalogs" of solutions to recurring.
Informatics 122 Software Design II
Session 07: C# OOP 4 Review of: Inheritance and Polymorphism. Static and dynamic type of an object. Abstract Classes. Interfaces. FEN AK - IT:
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
Informatics 122 Software Design II Lecture 5 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Adapters Presented By Zachary Dea. Definition A pattern found in class diagrams in which you are able to reuse an ‘adaptee’ class by providing a class,
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 Design Patterns: someone has already.
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
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.
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
COMP 121 Week 02. Agenda Review this week’s expected outcomesReview this week’s expected outcomes Review Guided Learning Activity solutionsReview Guided.
Chapter 1: Introduction to Design Patterns. SimUDuck Example.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
1 Unit 5 Design Patterns: Design by Abstraction. 2 What Are Design Patterns?  Design patterns are: Schematic descriptions of design solutions to recurring.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
1 Computer Science 340 Software Design & Testing Inheritance.
CS 210 Adapter Pattern October 19 th, Adapters in real life Page 236 – Head First Design Patterns.
Mohammed Al-Dhelaan CSci 253 Object Oriented Design Instructor: Brad Taylor 06/02/2009 Factory Method Pattern.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2.
05/26/2004www.indyjug.net1 Indy Java User’s Group May Knowledge Services, Inc.
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.
Object-Oriented Design and Programming (Java). 2 Topics Covered Today 2.3 Advanced Class Design –2.3.4 Design Patterns –2.3.5 Singleton Pattern –2.3.6.
Object Oriented Programming
CS 210 Final Review November 28, CS 210 Adapter Pattern.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
An Introduction To Design Patterns Jean-Paul S. Boodhoo Independent Consultant
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
CS 210 Introduction to Design Patterns August 29, 2006.
The Strategy Design Pattern © Allan C. Milne v
CS 210 Review October 3, 2006.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
It started with a simple … A highly successful duck pond simulation game called SimUDuck The game can show a large variety of duck swimming and making.
Inheritance ndex.html ndex.htmland “Java.
CS, AUHenrik Bærbak Christensen1 Compositional Design Principles The “GoF” principles Or Principles of Flexible Design.
IN 076 Pola Desain Perangkat Lunak Dosen: Hapnes Toba Oscar Karnalim
CS 210 Adapter Pattern October 17 th, Adapters in real life Page 236 – Head First Design Patterns.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
SE 461 Software Patterns Welcome to Design Patterns.
Intro to Design Pattern
Design Patterns: MORE Examples
Strategy Design Pattern
Strategy Pattern.
MPCS – Advanced java Programming
Low Budget Productions, LLC
Factory Patterns 1.
Behavioral Design Patterns
CMPE 135: Object-Oriented Analysis and Design October 24 Class Meeting
Strategy Design Pattern
Interfaces and Inheritance
SE-2811 Software Component Design
Object-Oriented Programming
SE-2811 Software Component Design
CMPE 135 Object-Oriented Analysis and Design March 21 Class Meeting
Inheritance and Polymorphism
Composite Design Pattern By Aravind Reddy Patlola.
Software Design Lecture : 27.
Presentation transcript:

Strategy Pattern1 Design Patterns 1.Strategy Pattern How to design for flexibility?

Strategy Pattern2 References Design Patterns: Elements of Reusable Object-Oriented Software By Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides (1995). Addison-Wesley. ISBN Design Patterns: Elements of Reusable Object-Oriented SoftwareGamma, Erich Richard HelmRalph JohnsonJohn VlissidesAddison-WesleyISBN Head First Design Patterns By Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates First Edition October 2004 ISBN 10: Eric Freeman Elisabeth FreemanKathy SierraBert Bates

Strategy Pattern3 Existing Duck application Duck quack() swim() display() //other duck-like methods… MallardDuck display() { // looks like a mallard} RedHeadDuck display() { // looks like a redhead } The display() method is abstract, since all duck subtypes look different Other duck types inherit from the Duck class... Each duck subtype is responsible for implementing its own display() method All ducks quack and swim. The superclass takes care of the implementation code

Strategy Pattern4 Inheritance All subclasses inherit the superclass’ properties –Variables and methods See Strategy0 project

Strategy Pattern5 Inheritance UML

Strategy Pattern6 Testing Mallard, RedHeadDuck classes

Strategy Pattern7 But Executives want to introduce fly capability quickly How to do it in a short time, like 2 days?

Strategy Pattern8 Solution #1 No sweat! –Add a method fly() in Duck –Continue to use inheritance

Strategy Pattern9 Add a method fly() in Duck Duck quack() swim() display() fly() //other duck-like methods… MallardDuck display() { // looks like a mallard} RedHeadDuck display() { // looks like a redhead } All subclasses inherit fly()

Strategy Pattern10 See Strategy1 class

Strategy Pattern11 Executing Strategy1

Strategy Pattern12 Everything OK? Think harder.

Strategy Pattern13 Something seriously wrong! Duck quack() swim() display() fly() //other duck-like methods… MallardDuck display() { // looks like a mallard} ReadHeadDuck display() { // looks like a redhead } All duck types now can fly including RubberDuck RubberDuck quack() { // overridden to Squeak } display() { // looks like a rubberduck }

Strategy Pattern14 Add an instance of RubberDuck

Strategy Pattern15 Executing Strategy2 … What?

Strategy Pattern16 Root cause? Applying inheritance to achieve re-use Poor solution for maintenance

Strategy Pattern17 How do we fix this? Using inheritance as before –Override the fly() method in rubber duck as in quack() Will it fix the problem? –See Strategy3

Strategy Pattern18 Strategy3

Strategy Pattern19 Executing Strategy3

Strategy Pattern20 Is the problem solved? Any new problems?

Strategy Pattern21 Wait a minute How about new duck types? –Decoy duck? Can’t quack Can’t fly How do we solve it?

Strategy Pattern22 Summary What have we done so far? What problems have we solved? What problems have we introduced in solving the problems? Is there a better way of doing things?

Strategy Pattern23 How about Interface? Take the fly() method out of Duck superclass And make a Flyable() interface –Only those ducks that fly are required to implement the interface Make a Quackable interface too

Strategy Pattern24 class Duck swim() display() //other duck-like methods… MallardDuck display() fly() quack() RedHeadDuck display() fly() quack() RubberDuck display() { quack() interface Flyable fly() Interface Quackable quack()

Strategy Pattern25 How about this Strategy4_interface solution?

Strategy Pattern26 But You shoot yourself in the foot by duplicating code for every duck type that can fly and quack! And we have a lot of duck types We have to be careful about the properties – we cannot just call the methods blindly We have created a maintenance nightmare!

Strategy Pattern27 Re-thinking: Inheritance has not worked well because –Duck behavior keeps changing –Not suitable for all subclasses to have those properties Interface was at first promising, but –No code re-use –Tedious Every time a behavior is changed, you must track down and change it in all the subclasses where it is defined –Error prone

Strategy Pattern28 #1 Design Principle Identify the aspects of your application that vary and separate them from what stays the same So what are variable in the Duck class? –Flying behavior –Quacking behavior Pull these duck behaviors out of the Duck class –Create new classes for these behaviors

Strategy Pattern29 How do we design the classes to implement the fly and quack behaviors? Goal: to keep things flexible Want to assign behaviors to instances of Duck –Instantiate a new MallardDuck instance –Initialize it with a specific type of flying –Be able to change the behavior dynamically

Strategy Pattern30 #2 Design Principle Program to a supertype, not an implementation Use a supertype to represent each behavior –FlyBehavior and QuackBehavior –Each implementation of a behavior will implement one of these supertypes In the past, we rely on an implementation –In superclass Duck, or –A specialized implementation in the subclass Now: Duck subclass will use a behavior represented in a supertype.

Strategy Pattern31

Strategy Pattern32

Strategy Pattern33 3 classes in code public interface FlyBehavior { public void fly(); } public class FlyWithWings implements FlyBehavior { public void fly() { System.out.println("I'm flying!!"); } public class FlyNoWay implements FlyBehavior { public void fly() { System.out.println("I can't fly"); }

Strategy Pattern34 public interface QuackBehavior { public void quack(); }

Strategy Pattern35 Specific behaviors by implementing interface QuackBehavior public class Quack implements QuackBehavior { public void quack() { System.out.println("Quack"); } public class Squeak implements QuackBehavior { public void quack() { System.out.println("Squeak"); } public class MuteQuack implements QuackBehavior { public void quack() { System.out.println(" >"); }

Strategy Pattern36

Strategy Pattern37 Program to a Supertype “Program to a Supertype” means: –Exploit polymorphism by programming to a supertype –The actual runtime object isn’t locked into the code –The declared type of the variable should be a supertype, usually an abstract class or interface –Objects assigned to those variables can be of any concrete implementations of the supertype –The class declaring them need not know about the actual object type

Strategy Pattern38 Integrating the Duck Behavior 1.Add 2 instance variables: Duck FlyBehavior flyBehavior QuackBehavior quackBehavior performQuack() Swim() Display() performFly() //OTHER duck-like methods Instance variables hold a reference to a specific behavior at runtime Behavior variables are declared as the behavior SUPERTYPE These general methods replace fly() and quack()

Strategy Pattern39 2. Implement performQuack() public abstract class Duck { // Declare two reference variables for the behavior interface types FlyBehavior flyBehavior; QuackBehavior quackBehavior; // All duck subclasses inherit these // etc public Duck() { } public void performQuack() { quackBehavior.quack(); // Delegate to the behavior class }

Strategy Pattern40

Strategy Pattern41 3. How to set the quackBehavior variable & flyBehavior variable public class MallardDuck extends Duck { public MallardDuck() { quackBehavior = new Quack(); // A MallardDuck uses the Quack class to handle its quack, // so when performQuack is called, the responsibility for the quack // is delegated to the Quack object and we get a real quack flyBehavior = new FlyWithWings(); // And it uses flyWithWings as its flyBehavior type } public void display() { System.out.println("I'm a real Mallard duck"); }

Strategy Pattern42

Strategy Pattern43 Testing the Duck code Type and compile: Duck class and the MallardDuck class FlyBehavior interface and the two behavior implementation classes (FlyWithwings.java and flyNoWay.java) QuackBehavior interface and 3 behavior implementation classes Test class (MiniDuckSimulator.java)

Strategy Pattern44 // 1. Duck class public abstract class Duck { // Reference variables for the behavior interface types FlyBehavior flyBehavior; QuackBehavior quackBehavior; // All duck subclasses inherit these public Duck() { } abstract void display(); public void performFly() { flyBehavior.fly(); // Delegate to the behavior class } public void performQuack() { quackBehavior.quack(); // Delegate to the behavior class } public void swim() { System.out.println("All ducks float, even decoys!"); }

Strategy Pattern45 2. FlyBehavior and two behavior implementation classes public interface FlyBehavior { public void fly(); } public class FlyWithWings implements FlyBehavior { public void fly() { System.out.println("I'm flying!!"); } public class FlyNoWay implements FlyBehavior { public void fly() { System.out.println("I can't fly"); }

Strategy Pattern46 // 3. QuackBehavior interface and 3 behavior implementation classes public interface QuackBehavior { public void quack(); } public class Quack implements QuackBehavior { public void quack() { System.out.println("Quack"); } public class Squeak implements QuackBehavior { public void quack() { System.out.println("Squeak"); } public class MuteQuack implements QuackBehavior { public void quack() { System.out.println(" >"); }

Strategy Pattern47 4. Type and compile the test class (MiniDuckSimulator.java) public class MiniDuckSimulator { public static void main(String[] args) { Duck mallard = new MallardDuck(); mallard.performQuack(); // This calls the MallardDuck's inherited performQuack() method, // which then delegates to the object's QuackBehavior // (i.e. calls quack() on the duck's inherited quackBehavior // reference) mallard.performFly(); // Then we do the same thing with MallardDuck's inherited // performFly() method. }

Strategy Pattern48 Strategy project

Strategy Pattern49 Run MiniDuckSimulator

Strategy Pattern50 Check-in We have built dynamic behavior in ducks e.g. a MallardDuck –The dynamic behavior is instantiated in the duck’s constructor How can we change the duck’s behavior after instantiation?

Changing a duck’s behavior after instantiation Set the duck’s behavior type through a mutator method on the duck’s subclass Strategy Pattern51

Strategy Pattern52 How to set behavior dynamically? 1.Add new methods to the Duck class public void setFlyBehavior (FlyBehavior fb) { flyBehavior = fb; } public void setQuackBehavior(QuackBehavior qb) { quackBehavior = qb; }

Strategy Pattern53 2. Make a new Duck type (ModelDuck.java) public class ModelDuck extends Duck { public ModelDuck() { flyBehavior = new FlyNoWay(); // Model duck has no way to fly quackBehavior = new Quack(); } public void display() { System.out.println("I'm a model duck"); }

Strategy Pattern54

Enabling ModelDuck to fly Use a mutator (setter) method to enable ModelDuck to fly Strategy Pattern55

Strategy Pattern56 3. Make a new FlyBehavior type (FlyRocketPowered.java) public class FlyRocketPowered implements FlyBehavior { public void fly() { System.out.println("I'm flying with a rocket"); }

Strategy Pattern57

Strategy Pattern58 4. Change the test class (MiniDuckSimulator.java), add the ModelDuck, and make the ModelDuck rocket-enabled Duck model = new ModelDuck(); model.performFly(); // call to performFly() delegates to the flyBehavior // object set in ModelDuck's constructor model.setFlyBehavior(new FlyRocketPowered()); // change the duck's behavior at runtime by // invoking the model's inherited behavior setter // method model.performFly();

Strategy Pattern59

Strategy Pattern60 Test again From mallard Due to flyBehavior = new FlyNoWay(); In constructor of ModelDuck Due to setter method inherited from Duck but set in model

Strategy Pattern61

Strategy Pattern62 Big Picture on encapsulated behaviors Reworked class structure

Strategy Pattern63 Summary Reworked class structure –ducks extending Duck –fly behaviors implementing FlyBehavior –quack behaviors implementing QuackBehavior Think of each set of behaviors as a family of algorithms Relationships: IS-A, HAS-A, IMPELMENTS Exercise: mark up the following diagram with the relationships above

Strategy Pattern64 Duck FlyBehavior flyBehavior QuackBehavior quackBehavior Swim() Display() performQuack() performFly() setFlyBehavior() setQuackbehavior() //OTHER duck-like methods MallardDuck display() RedHeadDuck display() RubberDuck display() Encapsulated fly behavior Encapsulated quack behavior

Strategy Pattern65 HAS-A can be better than IS-A Each duck has a FlyBehavior and a QuackBehavior to which it delegates flying and quacking Composition at work –Instead of inheriting behavior, ducks get their behavior by being composed with the right behavior object

Strategy Pattern66 Third Design Principle Favor composition over inheritance –More flexibility –Encapsulate a family of algorithms into their own set of classes –Able to change behavior at runtime

Strategy Pattern67 Strategy Pattern The strategy Pattern –Defines a family of algorithms, –Encapsulates each one, –Makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it