CHAPTER 7

image

Strategy Patterns (Or, Policy Patterns)

GoF Definition: Define a family of algorithms, encapsulate each one, and make them interchangeable. The strategy pattern lets the algorithm vary independently from client to client.

Concept

We can select the behavior of an algorithm dynamically at runtime.

Real–Life Example

In a football match, at the last moment, in general, if Team A is leading Team B by a score of 1-0, instead of attacking, Team A becomes defensive. On the other hand, Team B goes for an all-out attack to score.

Computer World Example

The above concept is applicable to a computer football game also. Or, we can think of two dedicated memories where upon fulfillment of one memory, we start storing the data in the second available memory. So, a runtime check is necessary before the storing of data, and based on the situation, we’ll proceed.

Illustration

We can understand the strategy pattern through the following program and class diagram. In the main function, we have tested for two arbitrary choices of users (though you can do as many as wish). Depending on the user’s input, our context objects will decide what choice should be set and displayed.

UML Class Diagram

9781484218013_unFig07-01.jpg

Package Explorer view

High-level structure of the parts of the program is as follows:

9781484218013_unFig07-02.jpg

Implementation

// IChoice.java

package choices;
public interface IChoice
{
        void myChoice(String s1, String s2);
}

//FirstChoice.java

package choices;

public class FirstChoice implements IChoice
{
        public void myChoice(String s1, String s2)
        {
                System.out.println("You wanted to add the numbers.");
                int int1, int2,sum;
                int1=Integer.parseInt(s1);
                int2=Integer.parseInt(s2);
                sum=int1+int2;
                System.out.println(" The result of the addition is:"+sum);
                System.out.println("***End of the strategy***");
        }
}
// SecondChoice.java

package choices;

public class SecondChoice implements IChoice
{
        public void myChoice(String s1, String s2)
        {
                System.out.println("You wanted to concatenate the numbers.");
                System.out.println(" The result of the addition is:"+s1+s2);
                System.out.println("***End of the strategy***");
        }
}

//Context.java

package contextofchoice;

import choices.IChoice;

public class Context
{
        IChoice myC;
        // Set a Strategy or algorithm in the Context
        public void SetChoice(IChoice ic)
        {
                myC = ic;
        }
        public void ShowChoice(String s1,String s2)
        {
                myC.myChoice(s1,s2);
        }
}

// StrategyPatternEx.java

package strategy.pattern.demo;
import java.io.IOException;
//For Java old versions-to take input from user
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
/* Java 5  added a nice utility class called Scanner, to get input from user */
import java.util.Scanner;

import contextofchoice.Context;
//import choices.*;
import choices.FirstChoice;
import choices.IChoice;
import choices.SecondChoice;

class StrategyPatternEx
{
        public static void main(String[] args) throws IOException
        {
                System.out.println("***Strategy Pattern Demo***");
                Scanner in= new Scanner(System.in);//To take input from user
                IChoice ic = null;
                Context cxt = new Context();
                String input1,input2;;
                //Looping twice to test two different choices
                try
                {
                        for (int i = 1; i <= 2; i++)
                        {
                                System.out.println("Enter an integer:");
                                input1 = in.nextLine();
                                System.out.println("Enter another integer:");
                                input2 = in.nextLine();
                                System.out.println("Enter ur choice(1 or 2)");
                                System.out.println("Press 1 for Addition, 2 for Concatenation");
                                String c = in.nextLine();

                                /*For Java old versions-use these lines to collect input from user
                                BufferedReader br = new BufferedReader( new InputStreamReader( System.in ));
                                String c = br.readLine();*/

                                if (c.equals("1"))
                                {
                                        /*If user input is 1, create object of FirstChoice (Strategy 1)*/
                                        ic = new FirstChoice();
                                }
                                else
                                {
                                        /*If user input is 2, create object of SecondChoice (Strategy 2)*/
                                        ic = new SecondChoice();
                                }
                                /*Associate the Strategy with Context*/
                                cxt.SetChoice(ic);
                                cxt.ShowChoice(input1,input2);
                        }
                }
                finally
                {
                        in.close();
                }
                System.out.println("End of Strategy pattern");
        }
}

Output

9781484218013_unFig07-03.jpg

Note

What is the power behind the strategy pattern?

  1. This pattern can provide dynamic behavior for us. It can help us to avoid dealing with complex algorithm-specific data structures.
  2. With this pattern, the same behavior can be expressed differently. So, users can have a wide variety of choices.

What are the challenges associated with the strategy pattern?

  1. The number of objects are increased in the system.
  2. Additional overhead is needed due to communication between the strategies and their contexts.
  3. Users need to be fully aware of all kinds of possible behaviors to avoid confusion.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.106.233