Hi guys,
as I'm looking into the MVC pattern, I thought I'd create a small application to understand a bit more.
Let's look at the code:
//model
package model;
public class StudentModel
{
private String name;
private String surname;
private int number;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public int getNumber()
{
return number;
}
public void setNumber(int number)
{
this.number = number;
}
}
//controller
package controller;
import model.StudentModel;
import view.StudentView;
public class StudentController
{
private StudentModel studentModel;
private StudentView studentView;
public StudentController(StudentModel studentModel, StudentView studentView)
{
super();
this.studentModel = studentModel;
this.studentView = studentView;
}
}
//view
package view;
public class StudentView
{
public void displayStudent(String name, String surname, int number){
System.out.println("Student is: " + name + " " + surname + "\n" + "Number: " + number);
}
}
//demo
import model.StudentModel;
import view.StudentView;
import controller.StudentController;
public class StudentDemo
{
public static void main(String[] args)
{
StudentView studentView = new StudentView();
StudentModel model = createStudent("John", "Smith", 34567);
StudentController studentController = new StudentController(model, studentView );
studentView.displayStudent(model.getName(), model.getSurname(), model.getNumber());
}
public static StudentModel createStudent(String name, String surname, int number){
StudentModel studentModel = new StudentModel();
studentModel.setName(name);
studentModel.setSurname(surname);
studentModel.setNumber(number);
return studentModel;
}
}
OK so, everything works OK, in the sense that I get printed what I expected. But then I run into a problem: what if I want to have multiple students? Does it mean that I have to replicate the code inside StudentDemo, something like this
StudentView studentView = new StudentView();
StudentModel model = createStudent("John", "Smith", 34567);
StudentController studentController = new StudentController(model, studentView );
studentView.displayStudent(model.getName(), model.getSurname(), model.getNumber());
StudentView studentView1 = new StudentView();
StudentModel model1 = createStudent("Jane", "Doe", 56783);
StudentController studentController1 = new StudentController(model1, studentView1 );
studentView.displayStudent(model1.getName(), model1.getSurname(), model1.getNumber());
...
It doesn't sound like a good approach...