Can View chat directly with Model?

2

In MVC the View serves to handle the entire user interface, the Model serves to contain the classes that represent the system and its business rules and < Controller performs the communication between View and Model (something like controlling the flow of data), following this line of reasoning I can conclude that both View and Model do not talk to each other. >

Here is a short example in Java for contextualizing:

ViewerPass Class:

public class ViewPessoaCadastro extends JFrame {            
    public ViewPessoaCadastro() {
        initComponents();
    }

    private void Salvar(ActionEvent evt) {//Clique
        //Salvar os dados.            
    }                       

    private void Listar(ActionEvent evt) {//Clique                        
        //Obtem todas as pessoas cadastradas e exibi para o usuario.
    }                           
}

Class ControllerPersonal:

public class ControllerPessoa {
    Pessoa pessoa;

    public ControllerPessoa(Pessoa pessoa) { 
        this.pessoa = pessoa;
    }

    public void salvar() { 
        pessoa.salvar();
    }

    public void alterar() { 
        pessoa.alterar();
    }

    public List<Pessoa> listarTodas() { 
        List<Pessoa> pessoas = pessoa.listarTodas();
        return pessoas;
    }

    public List<String> obterErrosValidacao() { 
        List<String> errosValidacao = pessoa.validar();
        return errosValidacao;
    }
}

Class Person:

public class Pessoa {      
    private String nome;
    private int idade;

    public Pessoa() { }

    public Pessoa(String nome, int idade) {
        this.nome = nome;
        this.idade = idade;
    }

    public void salvar() { 
        //Rotina para salvar no banco de dados.
    }

    public void alterar() { 
        //Rotina para registrar a alteração dos dados no banco de dados.
    }
    public List<Pessoa> listarTodas() {
        //Rotina para listar todas as pessoas salvar no banco de dados.
        ...            
    }

    public List<String> validar() { 
        //Rotina para validar a classe pessoa (Regras de negocio).
        ...
    }

    /*Getters e Setters*/
    public String getNome() { return nome; }

    public void setNome(String nome) { this.nome = nome; }

    public int getIdade() { return idade; }

    public void setIdade(int idade) { this.idade = idade; }
}

Questions

Considering the above example in Java I had the following doubt:

When I fill in the attributes of class Pessoa , I do this in the view by creating an object of type Pessoa and then I pass it in the constructor of class ControllerPessoa or I create a method in class ControllerPessoa that contains all the parameters that represent the attributes of class Pessoa ? Considering the above question is there any possibility of View chatting directly with the Model?

PS: Can give examples in other languages as well, but could preferably be Java itself.

    
asked by anonymous 29.08.2016 / 16:33

1 answer

2

In the Gof setting, the only communication allowed between Model and View is using Design Pattern Observer . It is okay for a view to "talk" to a model as long as this "conversation" is in the form of the Observer pattern, view can only observe changes to model to reflect this to the user. In this case and only in this case, the controller is not involved and the model and view can communicate. Otherwise, the controller should be invoked for communication between view and model .

What is common to help with this communication is the ViewHelper pattern that is located between the controller and the view . This pattern is intended to take the view data and convert it to a preformatted object to be sent to the controller . The controller can in turn have an association with model and it is the one that performs the action of retrieving the data from the view and persists the data in model .

In short, it is not appropriate for view to have any association with model , except in a single case that is when view model to reflect this to the user. This is done using the Observer pattern. Finally, to help the controller perform this communication, the ViewHelper pattern is commonly used.

Update

You can interpret this definition and apply it according to your understanding. The important thing is to follow the principles of MVC Design Pattern .

I'll give you an example: Imagine that you are developing in a web environment, where you can consider an HTML form as the View layer, the Servlet that intercepts the requests as the Controller layer and the domain classes as the Model layer . A very simple code would look something like this:

VIEW

<form method="post" action="cadastrar">
<input type="text" name="nome" placeholder="Nome da pessoa"/>
<input type="text" name="idade" placeholder="Idade da pessoa"/>
<input type="text" name="frase" placeholder="Frase predileta"/>
<button type="submit">Enviar</button>
</form>

A simple form that will send a person's name, age, and a favorite phrase to a "sign up" mapping.

VIEWHELPER

public class PessoaViewHelper implements IViewHelper{
   public Entidade getView(HttpServletRequest request) {
      Pessoa p = new Pessoa();
      p.setNome(request.getParameter("nome");
      p.setIdade(request.getParameter("idade");
      p.setFrasePredileta(request.getParameter("frase");
      return p;
   }
}

In this case, class Pessoa inherits Entidade . Therefore, your ViewHelper is extracting data from request from the browser and turning it into an object that is recognizable by the controller.

CONTROLLER

public class MyServlet extends HttpServlet {
   IViewHelper viewHelper;
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        viewHelper = new PessoaViewHelper();
        Pessoa pessoa = viewHelper.getView(req);

        //Nesse momento, seu objeto pessoa contém os dados da view extraídas pelo view helper
       //Aqui você executa sua lógica para fazer o que quiser com o model pessoa.
       //...
       resp.getWriter().write("Pessoa cadastrada...bla bla bla");
    }
}

Controller does not need to execute view extraction logic or execute validations, just because it now has an auxiliary, which is the viewhelper.

This was a very simplified example of how data extraction logic would work using viewhelper .

I hope I have helped.

    
29.08.2016 / 16:49