Created
February 22, 2024 11:22
-
-
Save alexjosesilva/bd0fb4891ffe1d947bd7d65a08f0a454 to your computer and use it in GitHub Desktop.
Strategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Interface Strategy | |
interface Strategy { | |
int execute(int a, int b); | |
} | |
// Implementações concretas das estratégias | |
class AddStrategy implements Strategy { | |
@Override | |
public int execute(int a, int b) { | |
return a + b; | |
} | |
} | |
class SubtractStrategy implements Strategy { | |
@Override | |
public int execute(int a, int b) { | |
return a - b; | |
} | |
} | |
class MultiplyStrategy implements Strategy { | |
@Override | |
public int execute(int a, int b) { | |
return a * b; | |
} | |
} | |
// Classe de contexto que utiliza a estratégia | |
class Context { | |
private Strategy strategy; | |
public Context(Strategy strategy) { | |
this.strategy = strategy; | |
} | |
public int executeStrategy(int a, int b) { | |
return strategy.execute(a, b); | |
} | |
} | |
// Classe principal para testar o padrão Strategy | |
public class Main { | |
public static void main(String[] args) { | |
// Criação de uma instância do contexto com uma estratégia específica | |
Context context = new Context(new AddStrategy()); | |
// Execução da estratégia de adição | |
int result1 = context.executeStrategy(10, 5); | |
System.out.println("Resultado da adição: " + result1); | |
// Mudança da estratégia para subtração | |
context = new Context(new SubtractStrategy()); | |
// Execução da estratégia de subtração | |
int result2 = context.executeStrategy(10, 5); | |
System.out.println("Resultado da subtração: " + result2); | |
// Mudança da estratégia para multiplicação | |
context = new Context(new MultiplyStrategy()); | |
// Execução da estratégia de multiplicação | |
int result3 = context.executeStrategy(10, 5); | |
System.out.println("Resultado da multiplicação: " + result3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment