Dúvidas com controller

1 resposta
K

Olá...

Estou criando um controller simples e estou com algumas dúvidas:

No controller eu tenho o seguinte trecho de código:

String  page	= null;

Command command = CommandFactory.getCommand(request.getParameter("action"));
		   			
page = command.execute(request);

e tenho a factory que cria os commands:

public static MovieCommand getCommand(String action) {

switch(Integer.parseInt(action)) {
  case 1:
	return new MovieCommand();
  default: return null;	
}

}

Esse esquema está funcionando legal...

Caso o parâmetro action seja igual a 1, o MovieCommand será instanciado.
Só que eu terei vários tipos de actions:

incluir movie
alterar movie
etc...

Qual seria a melhor forma de implementar isso, de forma que minha factory não fique gigantesca ?

Obrigado pela atenção!

1 Resposta

R

Não sei se a forma que estou usando é a melhor, até agora está funcionando bem, e bem simples:

package br.com.dogato.controle;

import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.dogato.controle.actions.*;	


public class PetController extends HttpServlet {
	
	private HashMap actions = new HashMap();
	
	public void init() throws ServletException {
		
		actions.put("login", new ActionLogin());
		actions.put("logout", new ActionLogout());
		actions.put("erro", new ActionErro());
		actions.put("cadUsu", new ActionCadastroCliente());
	}	
	
	private Action getAction(String chave){
		try{	
			System.out.println("Chave " + chave);
			Action acao = (Action)actions.get(chave);	
			if(acao == null){
				System.out.println("Acao nula");
				return	(Action)actions.get("login");
			}
			else{
				System.out.println(((Action)actions.get(chave)).getClass());
				return	(Action)actions.get(chave);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			return	(Action)actions.get("login");
		}
		
	}
	
	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		service(arg0, arg1);
	}

	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		service(arg0, arg1);
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String actionType = request.getParameter("actionType");
		System.out.println(actionType);
		Action acao = getAction(actionType);
		acao.execute(request,response);		
	}	

}
Criado 31 de julho de 2005
Ultima resposta 31 de jul. de 2005
Respostas 1
Participantes 2