package calculator; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CalcController2 { private CalcModel model; private CalcView2 view; /** * Create a controller with no view and no model. */ public CalcController2() { } /** * Returns the view of this controller. * * @return the view of this controller. */ public CalcView2 getView() { return this.view; } /** * Returns the model of this controller. * * @return the model of this controller. */ public CalcModel getModel() { return this.model; } /** * Sets the model of this controller to the given model. * * @param model * the new model of this controller. * @pre. model != null */ public void setModel(CalcModel model) { this.model = model; } /** * Sets the view of this controller to the given view. * * @param view * the new view of this controller. * @pre. view != null */ public void setView(CalcView2 view) { this.view = view; this.view.addSumListener(new SumListener()); this.view.addSubtractListener(new SubtractListener()); this.view.addMultiplyListener(new MultiplyListener()); this.view.addDivideListener(new DivideListener()); this.view.addClearListener(new ClearListener()); } /** * Abstract base class for classes that listen for arithmetic events (sum, * subtract, multiply, divide. */ private abstract class ArithmeticListener implements ActionListener { private int getUserValue() { int userValue = 0; try { userValue = Integer.parseInt(getView().getUserValue()); } catch (NumberFormatException ex) { } return userValue; } private void setCalculatedValue() { getView().setCalcValue("" + getModel().getCalcValue()); } protected abstract void doOperation(int userValue); @Override public void actionPerformed(ActionEvent action) { int userValue = this.getUserValue(); doOperation(userValue); this.setCalculatedValue(); } } private class SumListener extends ArithmeticListener { @Override protected void doOperation(int userValue) { getModel().sum(userValue); } } private class SubtractListener extends ArithmeticListener { @Override protected void doOperation(int userValue) { getModel().subtract(userValue); } } private class MultiplyListener extends ArithmeticListener { @Override protected void doOperation(int userValue) { getModel().multiply(userValue); } } private class DivideListener extends ArithmeticListener { @Override protected void doOperation(int userValue) { if (userValue != 0) { getModel().divide(userValue); } } } private class ClearListener extends ArithmeticListener { @Override protected void doOperation(int userValue) { getModel().clear(); } } }