Design Patterns Series - Part One: Strategy Pattern

Design Patterns Series – Part One: Strategy Pattern

The Strategy Pattern is a first pattern described in a series of post I’m planning to make regarding this topic. The Strategy pattern allows us to select a specific algorithm at runtime and its one of the simples design patterns to grasp.
The scenario described on the diagram below shows a simple usage of the strategy pattern.

Let’s say we have a HttpServlet which creates a report using data retrieved from the request parameters, or some other sources like database. and depending on which kind of report we want to create (PDF, DOC or HTML) chooses appropriate algorithm to do just that.
So w end up with common interface for creating reports called ‘ReportGenerator’ with a single method ‘generateReport(ReportData rd)’:

/*
 * Created by softwarepassion.com
 * Any information regarding license for this code snippets and
 * other copyright info can be found @softwarepassion.com
 * The author doesn't take any reposnsibility for the presented
 * code and design patterns solutions.
 * Please be advised that this code can contain errors!
 *
 */


package strategydesignpattern;

/**
 * Common interface for generating reports using different formats
 *
 * @author Krzysztof Grajek
 * @version 28-01-2011
 */

public interface ReportGenerator {

    /**
     * Generates report using provided report data
     * @param rd ReportData object carrying all info needed to produce report
     */

    public void generateReport(ReportData rd);
}

We have three different implementations of this interface, allowing us to generate report in a form of PDF, DOC or HTML format.
PDF Report Generator:

/*
 * Created by softwarepassion.com
 * Any information regarding license for this code snippets and
 * other copyright info can be found @softwarepassion.com
 * The author doesn't take any reposnsibility for the presented
 * code and design patterns solutions.
 * Please be advised that this code can contain errors!
 *
 */


package strategydesignpattern;

/**
 * Responsible for handling PDF reports
 *
 * @author Krzysztof Grajek
 * @version 28-01-2011
 */

public class PDFReportGenerator implements ReportGenerator {

    public void generateReport(ReportData rd) {
        System.out.println("Generating PDF report..." + rd.getTitle());
    }

}

Microsoft Word Generator:

/*
 * Created by softwarepassion.com
 * Any information regarding license for this code snippets and
 * other copyright info can be found @softwarepassion.com
 * The author doesn't take any reposnsibility for the presented
 * code and design patterns solutions.
 * Please be advised that this code can contain errors!
 *
 */


package strategydesignpattern;

/**
 * Responsible for handling reports in MS Word format
 *
 * @author Krzysztof Grajek
 * @version 28-01-2011
 */

public class MsDOCReportGenerator implements ReportGenerator{

    public void generateReport(ReportData rd) {
        System.out.println("Generating MS Word report.. " + rd.getTitle());
    }

}

HTML Report Generator:

/*
 * Created by softwarepassion.com
 * Any information regarding license for this code snippets and
 * other copyright info can be found @softwarepassion.com
 * The author doesn't take any reposnsibility for the presented
 * code and design patterns solutions.
 * Please be advised that this code can contain errors!
 *
 */


package strategydesignpattern;

/**
 * Responsible for generating reports in HTML format
 *
 * @author Krzysztof Grajek
 * @version 28-01-2011
 */

public class HTMLReportGenerator implements ReportGenerator{

    public void generateReport(ReportData rd) {
        System.out.println("Generating HTML report..." + rd.getTitle());
    }

}

All mentioned above generators use a single object (simple POJO class) containing the data needed to generate report ReportData

/*
 * Created by softwarepassion.com
 * Any information regarding license for this code snippets and
 * other copyright info can be found @softwarepassion.com
 * The author doesn't take any reposnsibility for the presented
 * code and design patterns solutions.
 * Please be advised that this code can contain errors!
 */


package strategydesignpattern;

/**
 * Used to transport data needed to produce report
 * in any form using {@link ReportGenerator}
 *
 * @author Krzysztof Grajek
 * @version 28-01-2011
 */

public class ReportData {

    private String title;
    private String description;
    //...other report related stuff needed to produce report

    //..getters and setters for the class fields
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
   
}

All of different kinds of generators can be used in our simple report servlet:

/*
 * Created by softwarepassion.com
 * Any information regarding license for this code snippets and
 * other copyright info can be found @softwarepassion.com
 * The author doesn't take any reposnsibility for the presented
 * code and design patterns solutions.
 * Please be advised that this code can contain errors!
 *
 */


package strategydesignpattern;

/**
 * Example class using {@code ReportGenerator} interface
 * This class mimmicks the behaviour of a http servlet, assuming that all needed
 * parameters for generating report are coming from the database or in the form
 * of servlet request parameters contained in a single {@code ReportData } object,
 * we choose one of the available report generators
 * to generate our report.
 *
 * @author Krzysztof Grajek
 * @version 28-01-2011
 */

public class MockReportServlet {

    private ReportGenerator reportGenerator;

    public void onGet(String request, String response){
        //1. get the data from the database, request parameters or any other source
        //in the form of ReportData object
        ReportData reportData = new ReportData();
        reportData.setTitle("Design Patterns Report for: Strategy Pattern");
        //2. Using the request parameter decide on which one of three report generators
        //to use when generating the report
       
        //3. Assuming that PDF generator was selected by the user generate PDF report
        if("PDF".equals(request)){
            reportGenerator = new PDFReportGenerator();
            reportGenerator.generateReport(reportData);
        }
    }
}

The source code for this example (in the form of Netbeans project) can be found here

One response on “Design Patterns Series – Part One: Strategy Pattern

  1. Sandeep January 29, 2011 at 9:25 am

    This article does capture the essence of strategy pattern. waiting for more to come.

    http://extreme-java.blogspot.com

Leave a Reply

Related Posts

    No Releated Posts