|
| 1 | +--- |
| 2 | +title: "Strategy Pattern in Java: Streamlining Object Behaviors with Interchangeable Algorithms" |
| 3 | +shortTitle: Strategy |
| 4 | +description: "Explore the Strategy design pattern in Java with a detailed guide and practical examples. Learn how to implement flexible and interchangeable algorithms effectively in your Java applications for enhanced design and maintenance." |
| 5 | +category: Behavioral |
| 6 | +language: en |
| 7 | +tag: |
| 8 | + - Decoupling |
| 9 | + - Extensibility |
| 10 | + - Gang of Four |
| 11 | + - Interface |
| 12 | + - Polymorphism |
| 13 | +--- |
| 14 | + |
| 15 | +## Também conhecido como |
| 16 | + |
| 17 | +* Policy |
| 18 | + |
| 19 | +## Intenção do Strategy Design Pattern |
| 20 | + |
| 21 | +Defina uma família de algoritmos em Java, encapsule cada um e torne-os intercambiáveis para aprimorar o desenvolvimento de software usando o padrão de design Strategy. O Strategy permite que o algoritmo varie independentemente dos clientes que o utilizam. |
| 22 | + |
| 23 | +## Explicação detalhada do padrão de estratégia com exemplos do mundo real |
| 24 | + |
| 25 | +Exemplo do Mundo Real |
| 26 | + |
| 27 | +> Um exemplo prático do padrão de projeto Strategy em Java é evidente em sistemas de navegação automotiva, onde a flexibilidade do algoritmo é fundamental. Diferentes algoritmos de navegação (como rota mais curta, rota mais rápida e rota panorâmica) podem ser usados para determinar o melhor caminho de um local para outro. Cada algoritmo encapsula uma estratégia específica para o cálculo da rota. O usuário (cliente) pode alternar entre esses algoritmos com base em suas preferências sem alterar o próprio sistema de navegação. Isso permite estratégias de navegação flexíveis e intercambiáveis dentro do mesmo sistema. |
| 28 | +
|
| 29 | +Em outras palavras |
| 30 | + |
| 31 | +> O padrão Strategy permite escolher o algoritmo mais adequado em tempo de execução. |
| 32 | +
|
| 33 | +De acordo com a Wikipédia |
| 34 | + |
| 35 | +> Na programação de computadores, o padrão Strategy (também conhecido como padrão de política) é um padrão de design de software comportamental que permite selecionar um algoritmo em tempo de execução. |
| 36 | +
|
| 37 | +Flowchart |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | +## Exemplo programático de padrão Strategy em Java |
| 42 | + |
| 43 | + |
| 44 | +Matar dragões é um trabalho perigoso. Com a experiência, fica mais fácil. Matadores de dragões veteranos desenvolveram diferentes estratégias de luta contra diferentes tipos de dragões. |
| 45 | + |
| 46 | +Vamos explorar como implementar a interface `DragonSlayingStrategy` em Java, demonstrando várias aplicações do padrão Strategy. |
| 47 | + |
| 48 | +```java |
| 49 | +@FunctionalInterface |
| 50 | +public interface DragonSlayingStrategy { |
| 51 | + |
| 52 | + void execute(); |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +```java |
| 57 | +@Slf4j |
| 58 | +public class MeleeStrategy implements DragonSlayingStrategy { |
| 59 | + |
| 60 | + @Override |
| 61 | + public void execute() { |
| 62 | + LOGGER.info("With your Excalibur you sever the dragon's head!"); |
| 63 | + } |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +```java |
| 68 | +@Slf4j |
| 69 | +public class ProjectileStrategy implements DragonSlayingStrategy { |
| 70 | + |
| 71 | + @Override |
| 72 | + public void execute() { |
| 73 | + LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!"); |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
| 77 | + |
| 78 | +```java |
| 79 | +@Slf4j |
| 80 | +public class SpellStrategy implements DragonSlayingStrategy { |
| 81 | + |
| 82 | + @Override |
| 83 | + public void execute() { |
| 84 | + LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"); |
| 85 | + } |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +E aqui está o poderoso `DragonSlayer`, que pode escolher sua estratégia de luta com base no oponente. |
| 90 | + |
| 91 | +```java |
| 92 | +public class DragonSlayer { |
| 93 | + |
| 94 | + private DragonSlayingStrategy strategy; |
| 95 | + |
| 96 | + public DragonSlayer(DragonSlayingStrategy strategy) { |
| 97 | + this.strategy = strategy; |
| 98 | + } |
| 99 | + |
| 100 | + public void changeStrategy(DragonSlayingStrategy strategy) { |
| 101 | + this.strategy = strategy; |
| 102 | + } |
| 103 | + |
| 104 | + public void goToBattle() { |
| 105 | + strategy.execute(); |
| 106 | + } |
| 107 | +} |
| 108 | +``` |
| 109 | + |
| 110 | +Finalmente, aqui está o `DragonSlayer` em ação. |
| 111 | + |
| 112 | +```java |
| 113 | +@Slf4j |
| 114 | +public class App { |
| 115 | + |
| 116 | + private static final String RED_DRAGON_EMERGES = "Red dragon emerges."; |
| 117 | + private static final String GREEN_DRAGON_SPOTTED = "Green dragon spotted ahead!"; |
| 118 | + private static final String BLACK_DRAGON_LANDS = "Black dragon lands before you."; |
| 119 | + |
| 120 | + public static void main(String[] args) { |
| 121 | + // GoF Strategy pattern |
| 122 | + LOGGER.info(GREEN_DRAGON_SPOTTED); |
| 123 | + var dragonSlayer = new DragonSlayer(new MeleeStrategy()); |
| 124 | + dragonSlayer.goToBattle(); |
| 125 | + LOGGER.info(RED_DRAGON_EMERGES); |
| 126 | + dragonSlayer.changeStrategy(new ProjectileStrategy()); |
| 127 | + dragonSlayer.goToBattle(); |
| 128 | + LOGGER.info(BLACK_DRAGON_LANDS); |
| 129 | + dragonSlayer.changeStrategy(new SpellStrategy()); |
| 130 | + dragonSlayer.goToBattle(); |
| 131 | + |
| 132 | + // Java 8 functional implementation Strategy pattern |
| 133 | + LOGGER.info(GREEN_DRAGON_SPOTTED); |
| 134 | + dragonSlayer = new DragonSlayer( |
| 135 | + () -> LOGGER.info("With your Excalibur you sever the dragon's head!")); |
| 136 | + dragonSlayer.goToBattle(); |
| 137 | + LOGGER.info(RED_DRAGON_EMERGES); |
| 138 | + dragonSlayer.changeStrategy(() -> LOGGER.info( |
| 139 | + "You shoot the dragon with the magical crossbow and it falls dead on the ground!")); |
| 140 | + dragonSlayer.goToBattle(); |
| 141 | + LOGGER.info(BLACK_DRAGON_LANDS); |
| 142 | + dragonSlayer.changeStrategy(() -> LOGGER.info( |
| 143 | + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!")); |
| 144 | + dragonSlayer.goToBattle(); |
| 145 | + |
| 146 | + // Java 8 lambda implementation with enum Strategy pattern |
| 147 | + LOGGER.info(GREEN_DRAGON_SPOTTED); |
| 148 | + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MELEE_STRATEGY); |
| 149 | + dragonSlayer.goToBattle(); |
| 150 | + LOGGER.info(RED_DRAGON_EMERGES); |
| 151 | + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.PROJECTILE_STRATEGY); |
| 152 | + dragonSlayer.goToBattle(); |
| 153 | + LOGGER.info(BLACK_DRAGON_LANDS); |
| 154 | + dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SPELL_STRATEGY); |
| 155 | + dragonSlayer.goToBattle(); |
| 156 | + } |
| 157 | +} |
| 158 | +``` |
| 159 | + |
| 160 | +Saída do programa: |
| 161 | + |
| 162 | +``` |
| 163 | +13:06:36.631 [main] INFO com.iluwatar.strategy.App -- Green dragon spotted ahead! |
| 164 | +13:06:36.634 [main] INFO com.iluwatar.strategy.MeleeStrategy -- With your Excalibur you sever the dragon's head! |
| 165 | +13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Red dragon emerges. |
| 166 | +13:06:36.634 [main] INFO com.iluwatar.strategy.ProjectileStrategy -- You shoot the dragon with the magical crossbow and it falls dead on the ground! |
| 167 | +13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Black dragon lands before you. |
| 168 | +13:06:36.634 [main] INFO com.iluwatar.strategy.SpellStrategy -- You cast the spell of disintegration and the dragon vaporizes in a pile of dust! |
| 169 | +13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Green dragon spotted ahead! |
| 170 | +13:06:36.634 [main] INFO com.iluwatar.strategy.App -- With your Excalibur you sever the dragon's head! |
| 171 | +13:06:36.634 [main] INFO com.iluwatar.strategy.App -- Red dragon emerges. |
| 172 | +13:06:36.635 [main] INFO com.iluwatar.strategy.App -- You shoot the dragon with the magical crossbow and it falls dead on the ground! |
| 173 | +13:06:36.635 [main] INFO com.iluwatar.strategy.App -- Black dragon lands before you. |
| 174 | +13:06:36.635 [main] INFO com.iluwatar.strategy.App -- You cast the spell of disintegration and the dragon vaporizes in a pile of dust! |
| 175 | +13:06:36.635 [main] INFO com.iluwatar.strategy.App -- Green dragon spotted ahead! |
| 176 | +13:06:36.637 [main] INFO com.iluwatar.strategy.LambdaStrategy -- With your Excalibur you sever the dragon's head! |
| 177 | +13:06:36.637 [main] INFO com.iluwatar.strategy.App -- Red dragon emerges. |
| 178 | +13:06:36.637 [main] INFO com.iluwatar.strategy.LambdaStrategy -- You shoot the dragon with the magical crossbow and it falls dead on the ground! |
| 179 | +13:06:36.637 [main] INFO com.iluwatar.strategy.App -- Black dragon lands before you. |
| 180 | +13:06:36.637 [main] INFO com.iluwatar.strategy.LambdaStrategy -- You cast the spell of disintegration and the dragon vaporizes in a pile of dust! |
| 181 | +``` |
| 182 | + |
| 183 | +## Quando usar o padrão de Strategy em Java |
| 184 | + |
| 185 | +Use o padrão Strategy quando: |
| 186 | + |
| 187 | +* Você precisar usar diferentes variantes de um algoritmo dentro de um objeto e quiser alternar entre algoritmos em tempo de execução. |
| 188 | +* Existem várias classes relacionadas que diferem apenas em seu comportamento. |
| 189 | +* Um algoritmo usa dados que os clientes não deveriam conhecer. |
| 190 | +* Uma classe define muitos comportamentos e estes aparecem como múltiplas instruções condicionais em suas operações. |
| 191 | + |
| 192 | +## Tutoriais de padrões de estratégia em Java |
| 193 | + |
| 194 | +* [Strategy Pattern Tutorial (DigitalOcean)](https://www.digitalocean.com/community/tutorials/strategy-design-pattern-in-java-example-tutorial) |
| 195 | + |
| 196 | +## Aplicações do Padrão Strategy no Mundo Real em Java |
| 197 | + |
| 198 | +* A interface `java.util.Comparator` do Java é um exemplo comum do padrão Strategy. |
| 199 | +* Em frameworks de GUI, gerenciadores de layout (como os do AWT e Swing do Java) são estratégias. |
| 200 | + |
| 201 | +## Benefícios e Compensações do Padrão Strategy |
| 202 | + |
| 203 | +Benefícios: |
| 204 | + |
| 205 | +* Famílias de algoritmos relacionados são reutilizadas. |
| 206 | +* Uma alternativa à subclasse para estender o comportamento. |
| 207 | +* Evita instruções condicionais para selecionar o comportamento desejado. |
| 208 | +* Permite que os clientes escolham a implementação do algoritmo. |
| 209 | + |
| 210 | +Compensações: |
| 211 | + |
| 212 | +* Os clientes devem estar cientes das diferentes estratégias. |
| 213 | +* Aumento no número de objetos. |
| 214 | + |
| 215 | +## Padrões de Projeto Java Relacionados |
| 216 | + |
| 217 | +* [Decorator](https://java-design-patterns.com/patterns/decorator/): Melhora um objeto sem alterar sua interface, mas está mais preocupado com responsabilidades do que com algoritmos. |
| 218 | +* [State](https://java-design-patterns.com/patterns/state/): Semelhante em estrutura, mas usado para representar comportamento dependente de estado em vez de algoritmos intercambiáveis. |
| 219 | + |
| 220 | +## Referências e Créditos |
| 221 | + |
| 222 | +* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) |
| 223 | +* [Functional Programming in Java](https://amzn.to/3JUIc5Q) |
| 224 | +* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq) |
| 225 | +* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) |
| 226 | +* [Refactoring to Patterns](https://amzn.to/3VOO4F5) |
0 commit comments