Strategy

Solução Proposta

Permite que um algoritmo varie independentemente dos clientes que o utilizam. As estratégias podem fornecer diferentes implementações do mesmo comportamento. 

Vantagens

Desvantagens

Exemplo

Em um jogo lutadores de MMA (Mixed Martial Arts) brasileiros e japoneses utilizam diversos estilos de arte marcial (karatê, judô e jui-jitsu). Durante a luta eles podem mudar a arte utilizada nos golpes para ataque e defesa. O jogador atuando como técnico decide como configurar cada lutador de acordo com esses diferentes estilos de arte marcial. 
 
Fighter chama o método de execução (toAttack/defense) utilizando a interface MartialArt vinculada toda vez que precisa executar o algoritmo do golpe. Ele não sabe com que tipo de estratégia trabalha ou como o algoritmo é executado. Client cria um objeto de estratégia específico (karate, Judo, Jui-Jitsu) e o passa para o Fighter correspondente (BrazilianFighter, JapaneseFighter). Esse Fighter expôe um setter que permite que os clientes substituam a estratégia associada a ele em tempo de execução. 

Diagrama de Classe

Strategy - Diagrama

Participantes

  • Strategy (MartialArt): Define uma interface comum para todos os algoritmos apoiados.

  • ConcreteStrategy (Karate, Judo, Jui-Jitsu): Implementa os algoritmos usando a interface de Strategy.

  • Context (Fighter): É configurado com um objeto ConcreteStrategy e mantém uma referência para um objeto Strategy.

Código

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public class Judo implements MartialArt {
    
    @Override
    public String toAttack() {
     return "Judo Ataque!";   
       
    }

    @Override
    public String toDefend() {
     return "Judo Defesa!";  
    }
    
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public class Karate implements MartialArt {
    
    @Override
    public String toAttack() {
     return "Karate Ataque!";   
       
    }
    
    @Override
    public String toDefend() {
     return "Karate Defesa!";  
    }
 
    
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public interface MartialArt {
    public String toAttack();
    public String toDefend();
    
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public class Client {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
            
        //Inicio da luta!!! 
        BrazilianFighter fighter1 = new BrazilianFighter();
        JapaneseFighter fighter2 = new JapaneseFighter();
                     
        Karate karat = new Karate();   
        Judo judo = new Judo();
        Jiujitsu jj = new Jiujitsu();
        
        fighter1.setMartialArt(karat);
        System.out.println(fighter1.toAttack());
        System.out.println(fighter1.toDefend());
        fighter1.setMartialArt(judo);
        System.out.println(fighter1.toAttack());
        System.out.println(fighter1.toDefend());
        
        fighter2.setMartialArt(judo);
        System.out.println(fighter2.toAttack());
        System.out.println(fighter2.toDefend());
        fighter2.setMartialArt(jj);
        System.out.println(fighter2.toAttack());
        System.out.println(fighter2.toDefend());
        
        //Fim da luta 
        
        // Inicio nova Luta!!
        
    }
    
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public abstract class Fighter {
    MartialArt martialArt;
        
    public void setMartialArt(MartialArt martialArt){
        this.martialArt = martialArt;
            
   }
    public abstract String toAttack();
        
    public abstract String toDefend();
           
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public class Jiujitsu  implements MartialArt {
  
    @Override
    public String toAttack() {
     return "Jiu-Jitsu Ataque!";   
       
    }

    @Override
    public String toDefend() {
     return "Jiu-Jitsu Defesa!";  
    }
    
    
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public class BrazilianFighter extends Fighter {

    public BrazilianFighter(){
        System.out.println("Lutador Brasileiro!");
    }
    @Override
    public String toAttack() {
       return martialArt.toAttack();
    }

    @Override
    public String toDefend() {
        return martialArt.toDefend();
    }
    
    
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package br.padroes.strategyFighter;

/**
 *
 * @author linus
 */
public class JapaneseFighter extends Fighter{
    
    public JapaneseFighter(){
         System.out.println("Lutador Japonês!");
    }
    
    @Override
    public String toAttack() {
       return martialArt.toAttack();
    }

    @Override
    public String toDefend() {
        return martialArt.toDefend();
    }
    
    
}
Clique aqui para fazer o download do código completo de implementação deste Design Pattern.

Padrões Relacionados