✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.
A simple, text-based MVC pattern should be implemented, which increments a counter upon user input via the console. A counter is incremented whenever a user presses "return" (model). The value that is displayed is the counter multiplied by a factor (value = counter * factor). Multiple views should be supported. The code - except the code for the model - is given as follows:
public class Quiz4 { static interface ModelListener { public void action(ModelEvent e); } static class ModelEvent { private final int counter; ModelEvent(int counter){ this.counter = counter; } public int getCounter() { return counter; } } static class View { View(Model model,int factor) { ModelListener l = e -> System.out.println("Counter x factor: " + e.getCounter()*factor); model.addListener(l); } } static class Control { public void requestInput(Model model) { while (true) { System.out.print("Press return: "); try { // read all characters until newline while (System.in.read()!='\n'); } catch (IOException e) { e.printStackTrace(); } model.setCounter(model.getCounter()+1); } } } public static void main(String[] args) { // One model, one controller, two views Model model = new Model(); View view = new View(model,1); View view1 = new View(model,2); Control control = new Control(); control.requestInput(model); }}
Which of the following implementations of the model are correct (i.e., bug-free and supporting the required behavior)?
a)
class Model { int counter = 0; List<ModelListener> ml = new ArrayList<>(); public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; } public void addListener(ModelListener l) { ml.add(l); } }
b)
class Model { int counter = 0; List<ModelListener> ml = new ArrayList<>(); public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; for (ModelListener l : ml) { l.action(new ModelEvent(this.counter)); } } public void addListener(ModelListener l) { ml.add(l); } }c) class Model { int counter = 0; ModelListener l = null; public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; if (l != null) { l.action(new ModelEvent(this.counter)); } } public void addListener(ModelListener l) { this.l = l; } }d) class Model { int counter = 0; List<ModelListener> ml = new ArrayList<>(); public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; for (ModelListener l : ml) { l.action(new ModelEvent(this.counter)); } } public void addListener(ModelListener l) { ml = null; } }