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.
- The strategy pattern encapsulate more than one algorithms with each one.
- It is provide one of several algorithms dynamically.
- It is provide the facility of exchanging algorithms.
- Data is transparent to the clients.
- 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 |