Skip to content

Instantly share code, notes, and snippets.

@gustavofonseca
Created May 30, 2011 18:35
Show Gist options
  • Save gustavofonseca/999271 to your computer and use it in GitHub Desktop.
Save gustavofonseca/999271 to your computer and use it in GitHub Desktop.
Strategy example in java(GoF design pattern) (not responsible for this code)
package br.padroes.gof.comportamental.strategy;
public class ClienteStrategy {
public static void main(String[] args) { Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy(3,4);
showResultado(resultA);
context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3,4);
showResultado(resultB);
context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3,4);
showResultado(resultC);
}
public static void showResultado(int resultado) {
System.out.println("Resultado: " + resultado);
}
}
package br.padroes.gof.comportamental.strategy;
public interface Strategy {
int execute(int a, int b);
}
package br.padroes.gof.comportamental.strategy;
public class Context {
private Strategy strategy;
// Constructor
public Context(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
}
package br.padroes.gof.comportamental.strategy;
public class ConcreteStrategySubtract implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyB's execute()");
return a - b;
// Do a subtraction with a and b
}
}
package br.padroes.gof.comportamental.strategy;
public class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyA's execute()");
return a + b;
// Do an addition with a and b
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment