Note: This pattern is taken from the The ServerSide.com.

Define a family of algorithms, encapsulate each, and make them interchangable in J2EE component. Strategy lets the algorithm vary independently from clients that use it. Article gives overview to use Strategy pattern in J2EE component with example. Use the strategy pattern when a. many related classes differ only in their behaviour. Strategies provide a way to configure a class with one of many behaviors. b. you need different variants of an algorithm. c. an algorithm uses data that client shouldn't know about. Use strategy pattern to avoid exposing complex, algorithm-specific data structure. d. a class defines many behaviors, and these appear as multiple condition statements in its operations.


import java.io.*;

public interface InterfaceAlgorithm
{

public void executeAlgorithm();


} // End of interface

// Beginning of class

class Algorithm1 implements InterfaceAlgorithm
{

public void executeAlgorithm() { prt(); }

public void prt() { System.out.println(" Class is Algorithm1."); }


}// End of class

// Beginning of class

class Algorithm2 implements InterfaceAlgorithm
{

public void executeAlgorithm() { prt(); }

public void prt() { System.out.println(" Class is Algorithm2."); }


} // End of class


// Beginning of class

class Context
{

public Context(InterfaceAlgorithm algo){ _algo = algo; }

public void contextInterface() {
_algo.executeAlgorithm(); }

private InterfaceAlgorithm _algo;

} //End of class



public class Driver
{

public static void main(String[] args)
{
Algorithm1 a1 = new Algorithm1();
Algorithm2 a2 = new Algorithm2();
Context context = new Context(a1);
context.contextInterface();
}

}
Site hosted by Angelfire.com: Build your free website today!