From Passion to Profession
  • Home
  • Notes
  • Projects
  • Resources
    • Discovery Log
    • Books I Read
    • Blogs I Visit
    • Tools I Use
  • Home
  • Notes
  • Projects
  • Resources
    • Discovery Log
    • Books I Read
    • Blogs I Visit
    • Tools I Use

Strategy Design Pattern Example

10/15/2013

0 Comments

 
Strategy pattern is a behavioral pattern that lets the algorithm vary independently from clients that use it by defining a family of algorithms, encapsulate each one, and make them interchangeable. An algorithm that's encapsulated in this way is called a strategy. Strategy is concerned with changing the behavior of an object.
Picture
source: GoF

overview

In strategy design pattern, each context object encapsulates (has) a concrete strategy object (algorithm/behavior) that is interchangeable which decides a particular way of processing request. There should be no switch statement inside Strategy. Move the switches out of Strategy class. You can apply strategy pattern to modularize your code so that big switch and all business logic are not all mixed up in the same place. However, strategy isn't a magic anti-switch solution.

The strategy classes conform to the same algorithm/behavior interface, usually defined with one method (e.g. offers a method named execute() or calculate(), etc.). A request to context object will be delegated to call the encapsulated strategy object’s algorithm/behavior (e.g. execute() or calculate()) method.

A strategy class encapsulates an action, not a thing. Think of Strategy pattern as a verb, or a noun that describe an action. So it wouldn't make a lot of sense to keep state in it. Therefore, the strategy implementations themselves are stateless.

strategy design pattern code sample

// Strategy base
public abstract class InsuranceStrategy {
    private double myIncome;

    protected InsuranceStrategy(double income) {
        myIncome = income;
    }

    protected double calculate() {
        return (myIncome - getAdjustment()) * getWeight() + getConstant();
    }

    protected abstract int getConstant();
    protected abstract double getWeight();
    protected abstract int getAdjustment();
}

// Concrete Strategies
public class InsuranceStrategyLow extends InsuranceStrategy{
    public int getConstant(){return 1;}
    public double getWeight(){return 1;}
    public int getAdjustment(){return 1;}
}

public class InsuranceStrategyMedium extends InsuranceStrategy{
    public int getConstant(){return 2;}
    public double getWeight(){return 2;}
    public int getAdjustment(){return 2;}
}

public class InsuranceStrategyHigh extends InsuranceStrategy{
    public int getConstant(){return 3;}
    public double getWeight(){return 3;}
    public int getAdjustment(){return 3;}
}

//
class Context {

    public double calculateInsurance(double income) {
        InsuranceStrategy strategy;

        if (income <= 100000) {
            strategy = new InsuranceStrategyLow(income);
        } else if (income <= 300000) {
            strategy = new InsuranceStrategyMedium(income);
        } else {
            strategy = new InsuranceStrategyHigh(income);
        }
        return strategy.calculate();
    }
}

when to use strategy design pattern

  • Many related classes differ only in their behavior.    
  • The behavior (strategy/algorithm) which decides a particular way of processing request is interchangeable in different variants.
  • The behavior (strategy/algorithm) changes happen per client’s decision. 
  • Hide complex, algorithm-specific data structure of the behavior (strategy/algorithm).
  • Helps unit testing by allowing you to mock strategy implementation.
  • To separate switch statements away from the place where you want to keep it closed to modifications.

comparison

Bridge vs. Strategy (very similar)
  • Same UML, different intents.
  • Bridge's intent is to decouple an abstraction from its implementation so that the two can vary independently, whereas Strategy's intent stresses making one algorithm/implementation interchangeable.
  • There is massive subclassing going on the Abstraction side and the nature of the Abstraction methods are more compositional, adaptive and far reaching, whereas Strategy has just a simple strategy delegation.
  • Bridge is classified under structural pattern, whereas Strategy is classified as a behavioral pattern.
  • Bridge's Implementor classes are named with noun; whereas Strategy classes are named with a verb or a noun that describe action.


State vs. Strategy

  • They both have context and both share the same UML but differ quite a bit in intents.
  • State design pattern is used to define and manage state of an object, whereas Strategy pattern is used to define a set of interchangeable algorithm and lets client to choose one of them.
  • States store a reference to the context object that contains them, or got passed the reference to the context. Strategies do not.
  • States provide the underlying implementation for all actions the context object does, whereas Strategies only handle a single, specific task.

Flyweight vs. Strategy
  • Flyweights are small strategy classes handled by the flyweight factory.
  • Both Strategy and Flyweight externalize extrinsic state.

references

  • Replace conditional logic with strategy pattern
0 Comments



Leave a Reply.

    Categories

    All
    Algorithm
    Concurrency
    CQ
    Data Structure
    Design Pattern
    Developer Tool
    Dynamic Programming
    Entrepreneur
    Functional Programming
    IDE
    Java
    JMX
    Marketing
    Marklogic
    Memory
    OSGI
    Performance
    Product
    Product Management
    Security
    Services
    Sling
    Social Media Programming
    Software Development

    Feed Widget

    Archives

    May 2020
    March 2020
    April 2018
    March 2018
    February 2018
    December 2017
    March 2017
    November 2016
    June 2016
    May 2016
    April 2016
    October 2015
    September 2015
    August 2015
    September 2014
    July 2014
    June 2014
    May 2014
    March 2014
    January 2014
    December 2013
    November 2013
    October 2013
    September 2013
    August 2013
    July 2013
    June 2013

    RSS Feed

in loving memory of my mother  and my 4th aunt
Photos from net_efekt, schani, visnup, Dan Zen, gadl, bobbigmac, Susana López-Urrutia, jwalsh, Philippe Put, michael pollak, oskay, Creative Tools, Violentz, Kyknoord, mobilyazilar