STRATEGY PATTERN. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.

Slides:



Advertisements
Similar presentations
Welcome to. Who am I? A better way to code Design Patterns ???  What are design patterns?  How many are there?  How do I use them?  When do I use.
Advertisements

18-1 Verifying Object Behavior and Collaboration Role playing – the act of simulating object behavior and collaboration by acting out an object’s behaviors.
Patterns Reusable solutions to common object-oriented programming problems When given a programming problem, re-use an existing solution. Gang of Four.
Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Design Patterns. What are design patterns? A general reusable solution to a commonly occurring problem. A description or template for how to solve a problem.
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 Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Katie C. O’Shea Dennis T. Tillman 11 February 2K2 Flyweight.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
CERN – European Organization for Nuclear Research GS Department – Administrative Information Services Design Patterns in Groovy Nicolas Décrevel Advanced.
Design Patterns Standardized Recurring model Fits in many location Opposite of customization Fundamental types of pattern Choose and use as desired and.
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
Design Patterns and Graphical User Interfaces Horstmann ,
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.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CSSE 374: 3½ Gang of Four Design Patterns These slides derived from Steve Chenoweth, Shawn Bohner, Curt Clifton, and others involved in delivering 374.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
Strategy Design Patterns CS 590L - Sushil Puradkar.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Computing IV Singleton Pattern Xinwen Fu.
CSE 403 Lecture 14 Design Patterns. Today’s educational objective Understand the basics of design patterns Be able to distinguish them from design approaches.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
ECE450S – Software Engineering II
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Mediator Kensho Tsuchihashi. Mediator Page 2 Table of Contents 1.What is Mediator? 2.What problem does Mediator solve? 3.Advantage and Disadvantage 4.Additional.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Introduction to Design Patterns. Questions What is a design pattern? Who needs design patterns? How different are classes and objects in APL compared.
Creational Patterns
What to know for the exam. Smalltalk will be used for questions, but there will not be questions about the grammar. Questions might ask – how particular.
Design Patterns Yonglei Tao. Design Patterns  A design pattern describes a recurring design problem, a solution, and the context in which that solution.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
Proxy.
OO Methodology Elaboration Iteration 2 - Design Patterns -
FACTORY METHOD. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
Design Patterns Introduction “Patterns are discovered, not invented” Richard Helm.
COMPOSITE. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory.
Interface Patterns. Adapter Provides the interface a client expects, using the services of a class with a different interface Note Avoid using object.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
CS 5150 Software Engineering Lecture 16 Program Design 3.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
PROTOTYPE. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory.
7 April 2004CSci 210 Spring Design Patterns 2 CSci 210.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
Examples (D. Schmidt et al)
Strategy: A Behavioral Design Pattern
Strategy Design Pattern
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Chapter 10 Design Patterns.
Software Design Patterns
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Introduction to Design Patterns
object oriented Principles of software design
Software Engineering Lecture 7 - Design Patterns
Design Patterns in Game Design
Strategy Design Pattern
Informatics 122 Software Design II
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

STRATEGY PATTERN

Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract factory Builder Prototype Singleton Adapter Bridge Composite Facade Flyweight Proxy Chain of Responsibility Command Iterator Mediator Memento State Strategy Visitor Observer

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

Examples: Sorting  Different types of sorts have different characteristics  Shellsort  No extra space needed  Fast but not O(n*log(n))  Very fast on nearly sorted data  Does comparatively well on small lists  Quicksort  Average case is O(n*log(n))  Relatively poor performance on short lists  Sorts in place  MergeSort  Worst case is O(n*log(n))  Requires O(n) extra space  Stable  Have a sorted list container, which one gives a sort algorithm  SortedList studentRecords = new SortedList( new ShellSort() ); studentRecords.add( "Sam" ); etc.

Applicability  Use the Strategy pattern when  you need different variants of an algorithm  an algorithm uses data that clients shouldn't know about  a class defines many behaviors, and these appear as multiple switch statement in the classes operations  many related classes differ only in their behavior

Consequences  Families of related algorithms Alternative to subclassing of Context  What is the big deal? You still subclass Strategy!  Eliminates conditional statements  Replace in Context code like: switch ( flag ) { case A: doA(); break; case B: doB(); break; case C: doC(); break; }  With code like: strategy.do();

Consequences  Gives a choice of implementations  Clients must be aware of different Strategies  Communication overhead between Strategy and Context  Increase number of objects

Implementation  Defining the Strategy and Context interfaces  How does data flow between them  Context pass data to Strategy  Strategy has point to Context, gets data from Context  Making Strategy objects optional  Give Context default behavior  If default used no need to create Strategy object

Example: Strategy  a simplified graphing program that can present data as a line graph or a bar chart  Since each plot will appear in its own frame, our base PlotStrategy class will be derived from JFrame:

PlotStrategy class public abstract class PlotStrategy extends JFrame { protected float[] x, y; protected Color color; protected int width, height; public PlotStrategy(String title) { super(title); width = 300; height =200; color = Color.black; addWindowListener(new WindAp(this)); } // public abstract void plot(float xp[], float yp[]); // public void setPenColor(Color c) { color = c; }

class WindAp extends WindowAdapter { JFrame fr; public WindAp(JFrame f) { fr = f; //copy Jframe instance } public void WindowClosing(WindowEvent e) { fr.setVisible(false); //hide window }

The Context  The Context class is the traffic cop that decides which strategy is to be called  The decision is usually based on a request from the client program  All that the Context needs to do is to set a variable to refer to one concrete strategy or another

The Context public class Context { //this object selects one of the strategies to be used for plotting //the plotStrategy variable points to selected strategy private PlotStrategy plotStrategy; float x[], y[]; //data stored here // public Context() { setLinePlot(); //make sure it is not null } // //make current strategy the Bar Plot public void setBarPlot() { plotStrategy = new BarPlotStrategy(); } // //make current strategy the Line Plot public void setLinePlot() { plotStrategy = new LinePlotStrategy(); }

// //call plot method of current strategy public void plot() { plotStrategy.plot(x, y); } // public void setPenColor(Color c) { plotStrategy.setPenColor(c); } // public void readData(String filename) { //read data from datafile somehow }

Test Program  This simple program is just a panel with two buttons that call the two plots:

Line Graph Button class public class JGraphButton extends JButton implements Command { Context context; public JGraphButton(ActionListener act, Context ctx) { super("Line graph"); //button label addActionListener(act); //add listener context = ctx; //copy context } // public void Execute() { context.setPenColor(Color.red); //set color of plot context.setLinePlot(); //set kind of plot context.readData("data.txt"); //read the data context.plot(); //plot the data }

The Line and Bar Graph Strategies  The two strategy classes are pretty much the same:  they set up the window size for plotting  call a plot method specific for that display panel

Line graph Strategy public class LinePlotStrategy extends PlotStrategy { LinePlotPanel lp; public LinePlotStrategy() { super("Line plot"); lp = new LinePlotPanel(); getContentPane().add(lp); } public void plot(float[] xp, float[] yp) { x = xp; y = yp; //copy in data findBounds(); //sets maxes and mins setSize(width, height); setVisible(true); setBackground(Color.white); lp.setBounds(minX, minY, maxX, maxY); lp.plot(xp, yp, color); //set up plot data repaint(); //call paint to plot }

Drawing Plots in Java  We create a PlotPanel class based on JPanel and derive two classes from it for the actual line and bar plots:

Base class: PlotPanel public class PlotPanel extends JPanel { float xfactor, yfactor; int xpmin, ypmin, xpmax, ypmax; float minX, maxX, minY, maxY; float x[], y[]; Color color; // public void setBounds(float minx, float miny, float maxx, float maxy) { minX=minx; maxX= maxx; minY=miny; maxY = maxy; } // public void plot(float[] xp, float[] yp, Color c) { x = xp; //copy in the arrays y = yp; color = c; //and color

//compute bounds and sclaing factors int w = getWidth() - getInsets().left - getInsets().right; int h = getHeight() - getInsets().top - getInsets().bottom; xfactor = (0.9f * w) / (maxX - minX); yfactor = (0.9f * h)/ (maxY - minY); xpmin = (int)(0.05f * w); ypmin = (int)(0.05f * h); xpmax = w - xpmin; ypmax = h - ypmin; repaint(); //this causes the actual plot } // protected int calcx(float xp) { return (int)((xp-minX) * xfactor + xpmin); } protected int calcy(float yp) { int ypnt = (int)((yp-minY) * yfactor); return ypmax - ypnt; }

Derived classe: LinePlotPanel public class LinePlotPanel extends PlotPanel { public void paint(Graphics g) { int xp = calcx(x[0]); //get first point int yp = calcy(y[0]); g.setColor(Color.white); //flood background g.fillRect(0,0,getWidth(), getHeight()); g.setColor(Color.black); //draw bounding rectangle g.drawRect(xpmin, ypmin, xpmax, ypmax); g.setColor(color); //draw line graph for(int i=1; i< x.length; i++) { int xp1 = calcx(x[i]); //get n+1st point int yp1 = calcy(y[i]); g.drawLine(xp, yp, xp1, yp1); //draw line xp = xp1; //copy for next loop yp = yp1; }

Example output