Model-View-Controller - Part 2

Let's start the example by looking at the model. The Model is really, really, really, really, really easy so that there is no confusion. We want to learn the MVC structure here, not struggle with the underlying code!

The class here is called CalculatorModel, and has methods to add, subtract, divide and multiply as you would expect in a normal calculator. There are also methods to get the answer, set the initial value of the calculator model and reset the value of the answer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class CalculatorModel
{
    private double answer, initial_number;

    // Constructor sets both numbers.
    public CalculatorModel()
    {
        answer = 0.0;
        initial_number = 0.0;
    }

    // Adds a number to the existing answer.
    public void doAddition(double y)
    {
        answer = answer + y;
    }

    // Subtracts a number to the existing answer.
    public void doSubtraction(double y)
    {
        answer = answer - y;
    }

    // Multiplies the existing answer by a number.
    public void doMultiply(double y)
    {
        answer = answer * y;
    }

    // Divides the existing answer by a number.
    public void doDivision(double y)
    {
        answer = answer / y;
    }

    // Gets the current answer.
    public double getAnswer()
    {
        return answer;
    }

    // Sets the current answer.
    public void setAnswer(double new_answer)
    {
        answer = new_answer;
    }

    // Sets the initial number.
    public void setInitialNumber(double new_initial)
    {
        initial_number = new_initial;
    }

    // Sets the answer to be the initial number.
    public void reset()
    {
        answer = initial_number;
    }
}
Bear in mind that although the methods are public, the values are private. This means that you must use the set and get methods in the class to get the values of the variables.

Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict