Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.

Slides:



Advertisements
Similar presentations
Chain of Responsibility Pattern Gof pp Yuyang Chen.
Advertisements

GoF State Pattern Aaron Jacobs State(305) Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Creational Patterns, Abstract Factory, Builder Billy Bennett June 11, 2009.
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Bridge Pattern.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
Plab – Tirgul 12 Design Patterns
Software Design and Documentation Individual Presentation: Composite Pattern 9/11/03.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
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.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Abstract Factory Pattern.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Composite Design Pattern. Motivation – Dynamic Structure.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Composit Pattern.
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
Design Patterns.
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.
Case Studies on Design Patterns Design Refinements Examples.
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
CS 4240: More Design Patterns Readings: Chap. 9. Let’s Recap Some Ideas and Strategies We’ll assume some design-planning is useful up-front Design with.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Decorator, Strategy, State Patterns.
Strategy Design Patterns CS 590L - Sushil Puradkar.
GoF: Document Editor Example Rebecca Miller-Webster.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
Structural Design Patterns
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Command Pattern.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
OO Methodology Elaboration Iteration 2 - Design Patterns -
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Billy Bennett June 22,  Intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
STRATEGY PATTERN. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Template Method Pattern (Behavioral) ©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.
Stéphane Ducasse 1 Strategy.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
STRATEGY PATTERN By Michelle Johnson. BACKGROUND Behavioral Pattern Allow you to define a family of algorithms, encapsulate each one, and make them interchangeable.
The State Design Pattern A behavioral design pattern. Shivraj Persaud
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Command Pattern. Intent encapsulate a request as an object  can parameterize clients with different requests, queue or log requests, support undoable.
Design Patterns: MORE Examples
Strategy: A Behavioral Design Pattern
Design Patterns: Brief Examples
Strategy Design Pattern
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University
Software Design and Architecture
Design Patterns A Case Study: Designing a Document Editor
Jim Fawcett CSE776 – Design Patterns Summer 2003
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
DESIGN PATTERNS : Strategy Pattern
Design pattern Lecture 9.
Strategy Design Pattern
Informatics 122 Software Design II
Presented by Igor Ivković
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern

Intent Define a family of algorithm, encapsulate each one, and make them interchageable. Strategy lets the algorithm vary independently from clients that use it. Also known as Policy pattern

Motivation Many algorithm exists for breaking a stream of text into lines. Hard-wiring all such algorithms into the classes is not desirable:  Clients get more complex if they include the linebreaking.  Different algorithm will be appropriate at different times.  It ’ s difficult to add new algorithms and vary existing ones when linebreaking is an integral part of a client.

Motivation(2) We avoid the problems by defining the classes encapsulate different linebreaking algorithms.

Applicability Use the Strategy pattern when Many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors. You need different variants of an algorithm.  algorithms reflecting different space/time trade-offs.  Strategies can be used when these variants are implemented as a class hierarchy of algorithms.

Applicability(2) An algorithm uses data-structure that clients shouldn ’ t know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures. A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

Participants Strategy(Compositor)  declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy. ConcreteStrategy  implements the algorithm using the Strategy interface.

Paritcipants(2) Context(Composition)  is configured with a ConcreteStrategy object.  maintains a reference to a Strategy object.  may define an interface that lets Strategy access its data.

Collaborations Strategy and Context interact to implement the chosen algorithm.  A context may pass all data required by the algorithm to the strategy when the algorithm is called.  Alternatively, the context can pass itself as an argument to Strategy operations. That lets the strategy call back on the context as required.

Collaborations(2) A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively. There is often a family of ConcreteStrategy classes for a client to choose from.

Consequences Families of related algorithms.  Hierarchies of Strategy classes define a family of algorithms or behaviors for contexts to reuse. Inheritance can help factor out common functionality of the algorithms.

Consequences(2) An alternative to subclassing.  another way to support a variety of algorithms or behaviors.  Subclassing:mixes the algorithm implementation with context ’ s, making Context harder to understand, maintain, and extend. Can not vary the algorithm dynamically.  Strategy: vary the algorithm independently of its context, making it easier to switch, understand, and extend.

Consequence(3) Strategies eliminate conditional statements.  When different behaviors are lumped into one class, it ’ s hard to avoid using conditional statements to select the right one.  Encapsulating the behavior in separate Strategy classes eliminates these conditional statements.  Code containing many conditional statements often indicates the need to apply the Strategy pattern.

Consequence(4) A choice of implementations.  Strategies can provide different implementations of the same behavior. The client can choose among strategies with different time and space trade-offs.

Consequence(5) Client must be aware of different Strategies.  A potential drawback: a client must understand how Strategies differr before it can select the appropriate one. Clients might be exposed to implementation issues.  You should use Strategy pattern only when the variation in behavior is relevant to Clients.

Consequence(6) Communication overhead between Strategy and Context  The Strategy interface is shared by all ConcreteStrategy classes whether the algorithms they implement are trivial or complex.  Some extra information may be passed to algorithm but not used.  If this is an issue, then you ’ ll need tighter coupling between Strategy and Context.

Consequence(7) Increased number of objects  Strategies increase the number of objects in an application.  Sometimes you reduce this overhead by implementing strategies as stateless objects that contexts can share.

Implementation Consider the following implementation issues:  Defining the Strategy and Context interfaces.  Strategies as template parameters.  Making Strategy objects optional.

Defining the Strategy and Context interfaces. The interfaces must give a ConcreteStrategy efficient access to any data it needs from a context, and vice versa.  Context pass data in parameters to Strategy operations.  A context pass itself as an argument, and the strategy requests data from the context explicitly. (Alternatively, the strategy can store a reference to its context, eliminating the need to pass anything.) But this couples Strategy and Context closely.

Strategies as template parameter In C++, templates can be used to configure a class with a strategy if  the Strategy can be selected as compile-time, and  it does not have to be changed at run-time. template class Context{ void Operation() {theStrategy.DoAlgorithm();} private Astrategy theStrategy; } class MyStrategy{public: void DoAlgorithm();}; Context aContext;

Making Strategy objects optional The Context class may be simplified if it ’ s meaningful not to have a Strategy object. Context checks to see if it has a Strategy object before accessing it.  If there is one, Context uses it normally.  If there is no one, Context carries out default behavior.

Sample Code The code for Composition class Composition{ public: Composition(Compositor *); void Repair(); private: Compositor* _compositor; Component* _Components;//the list of components int_componentCount; //the number of components int * _lineBreaks; //the Composition ’ s line width //in components int_lineCount; //the number of lines. }

Sample Code(2) The code for abstract Compositor class Compositor{ public: virtual int Compose( Coord natural[], Coord stretch[], Coord shrink[], int componentCount, int lineWidth, int breaks[] ) = 0; protected: Compositor(); }

Sample Code(3) Code for Repair operation void Composition::Repair() { Coord *natural; Coord *stretchability; Coord *shrinkability; intcomponentCount; int*breaks; … intbreakCount = _Compositor->Compose( natural, stretchability, shrinkability, componentCount, _lineWidth, breaks) … }

Sample Code(4) Code for Concrete Compositors class SimpleCompositor : public Compositor(){ public: simpleCompositor(); virtual int Compose( Coord natural[], Coord stretch[], Coord shrink[], int componentCount, int lineWidth, int breaks[] ); };

Sample Code(5) Code for instantiate Composition Composition* quick = new Composition(new SimpleCompositor);

Related Patterns Flyweight:  Strategy objects often make good flyweights.