I've read about state pattern and now I'm looking to further my knowledge by exploring a Swing application (exple : calculator) that implements it.
where can I find such a tutorial ?
it must showcase a really simple application that uses S开发者_如何学Pythonwing. I'm confused about how the State Pattern could be used in a Swing project ?
I really don't think that a calculator application is a good match for State pattern. A simple calculator does not have too many states, maybe on/off but that's too trivial. A drawing tool is a better match.
If you really want to develop a calculator based on the state pattern you really need to be quite creative. But why not? You could invent/implement a calculator where the basic operations (addition, substraction, multiplication, division) are modes (states):
public enum Modes {ADDITION, SUBTRACTION, MULITPLICATION, DIVISION}
public interface Mode {
double calculate(double a, double b);
}
public class AdditionMode implements Mode {
public double calculate(double a, double b) {
return (a+b);
}
}
// similiar classes for other math operation modes
public class Calculator {
private Mode mode;
public setMode(Modes mode) {
switch (mode) {
case ADDITION: this.mode = new AdditionMode();
// ...
}
}
public double calculate(double a, double b) {
return mode.calculate(a, b);
}
}
This is a very simple and basic draft and, of course, doesn't cover the View part (Swing dialog or whatever). On the dialog you could use four radio buttons to set the modes, a text field to capture input and a text field or label to print the actual result.
A sample you find here
I used this pattern in a swing application to represent a selected a drawing tool (line,polygon, etc.).
A full application that uses the state pattern in this way is JHotDraw
EDIT: For a calculator it could be used to map keystrokes (entered digits and operators) in calculation mode (== state) and in graph drawing mode (2nd state) for zoom and movement of the displayed graph.
To represent a mode like DEG, RAD, and GRA (degrees,radians) you shouldn't use the state pattern. This would be over engineered.
精彩评论