Design Pattern Basic Tutorial

adplus-dvertising
Strategy Pattern
Previous Home Next

The strategy pattern is also know as policy pattern. in which the algorithm is selected at the runtime. formally we can say that it is a family of algorithm, in which the algorithm is encapsulate each one.

Benefit and use of Strategy
  1. The strategy pattern encapsulate more than one algorithms with each one.
  2. It is provide one of several algorithms dynamically.
  3. It is provide the facility of exchanging algorithms.
  4. Data is transparent to the clients.
  5. Reduce the conditional statements.

Example

package r4r;
interface Cookies {
public void print();
}
class One implements Cookies {
public void print() {
System.out.println("This is your turn");
}
}
class Two implements Cookies {
public void print() {
System.out.println("Never too late to start");
}
}
class Zero implements Cookies {
public void print() {
System.out.println("You got nothing in your hand");    
}
}
class Dice {
public int Playit() {
return (int)(Math.random()*6)+1;
}
}
public class strategytest {
static void Fortune() {
int luckyNum = new Dice().Playit();
Cookies c;
switch (luckyNum) {
case 2: c = new Two();
break;
case 1: c = new One();
break;
//more
default: c = new Zero();
}
c.print();
}
public static void main(String[] args) {
Fortune();
}
}
Previous Home Next