Java 中的状态模式
我已经阅读了有关状态模式的内容,现在我希望通过探索实现它的 Swing 应用程序(例如:计算器)来进一步加深我的知识。
我在哪里可以找到这样的教程?
它必须展示一个使用 Swing 的非常简单的应用程序。我对如何在 Swing 项目中使用状态模式感到困惑?
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 Swing. I'm confused about how the State Pattern could be used in a Swing project ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我真的不认为计算器应用程序与状态模式非常匹配。一个简单的计算器没有太多的状态,也许是开/关,但这太微不足道了。绘图工具是更好的搭配。
如果你真的想开发一个基于状态模式的计算器,你真的需要非常有创意。但为什么不呢?您可以发明/实现一个计算器,其中基本运算(加法、减法、乘法、除法)是模式(状态):
这是一个非常简单和基本的草案,当然,不涵盖视图部分(Swing 对话框或任何)。在对话框中,您可以使用四个单选按钮来设置模式、一个用于捕获输入的文本字段以及一个用于打印实际结果的文本字段或标签。
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):
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.
您可以在此处找到示例,
我在一个 Swing 应用程序来表示选定的绘图工具(直线、多边形等)。
以这种方式使用状态模式的完整应用程序是 JHotDraw
编辑:对于计算器,它可能是用于在计算模式(==状态)和图形绘制模式(第二状态)下映射击键(输入的数字和运算符),以缩放和移动显示的图形。
要表示 DEG、RAD 和 GRA(度、弧度)等模式,不应使用状态模式。这将是过度设计的。
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.