
本文讲解在 swing 桌面应用中绘制序列图的核心原则:优先建模领域逻辑而非 ui 细节,通过分层抽象(领域层 vs. 表现层)构建清晰、可维护的 uml 序列图,并提供 atm 登录与取款流程的典型示例。
本文讲解在 swing 桌面应用中绘制序列图的核心原则:优先建模领域逻辑而非 ui 细节,通过分层抽象(领域层 vs. 表现层)构建清晰、可维护的 uml 序列图,并提供 atm 登录与取款流程的典型示例。
在面向对象系统建模中,序列图(Sequence Diagram)的核心价值不在于“画全所有类”,而在于精准表达特定场景下对象间的时序协作关系。对于基于 Java Swing 的 ATM 系统,关键在于明确建模目标——是揭示业务本质(如“客户凭 PIN 登录并成功取款”),还是记录技术实现细节(如 JButton 如何触发 ActionListener)。答案通常是前者:序列图应聚焦于领域对象(Customer、Account、ATM、Transaction)之间的职责流转,而非 Swing UI 组件的事件分发链路。
这并非忽略 UI,而是采用分层建模策略:
- 领域层序列图:以 Customer.login()、Account.withdraw()、ATM.processWithdrawal() 等业务方法为交互主线,参与者仅包含 Customer、Account、ATM、Transaction、Admin(必要时)等核心领域对象。UI 角色由隐式“Actor”(如 «Customer» 或 «Admin»)表示,或用一个轻量级 UIController 作为入口代理,避免污染业务逻辑流。
- 表现层序列图(可选):若需说明 UI 响应机制(如按钮点击 → 事件处理 → 领域调用),可单独绘制一张简化的图,参与者包括 JFrame、JButton、ActionListener 实现类及 ATMService(封装领域调用的门面),但此图应服务于架构设计审查,而非需求或领域分析。
以下是以“客户登录并取款”为例的领域层序列图核心逻辑(UML 文本描述,可直接导入 PlantUML 或 StarUML):
@startuml title Customer Login and Withdrawal Sequence actor "«Customer»" as customer participant "ATM" as atm participant "Customer" as cust_obj participant "Account" as account participant "Transaction" as tx customer -> atm: login(accountNumber, pin) atm -> cust_obj: findCustomerByAccount(accountNumber) cust_obj --> atm: Customer object atm -> cust_obj: verifyPIN(pin) cust_obj --> atm: true/false alt PIN verification successful atm -> account: loadByAccountNumber(accountNumber) account --> atm: Account object atm -> account: withdraw(amount) account -> tx: createWithdrawalTransaction(amount) tx --> account: Transaction object account --> atm: success atm --> customer: "Login OK; Balance: $X" customer -> atm: withdraw(200.0) atm -> account: withdraw(200.0) account -> tx: createWithdrawalTransaction(200.0) tx --> account: Transaction object account --> atm: success atm --> customer: "Withdrawal confirmed" else atm --> customer: "Invalid PIN" end @enduml
✅ 关键实践建议:
立即学习“Java免费学习笔记(深入)”;
- 禁止将 JFrame、JTextField 等 Swing 类直接作为序列图参与者——它们属于技术实现,会掩盖业务意图;
- 用 «Actor» 或抽象控制器(如 ATMUI)代表用户交互起点,保持领域对象纯净;
- 每个序列图只描述一个主场景(如“管理员添加新客户”、“生成交易回执”),避免大而全的“总图”;
- 数据库访问应封装在领域对象内部(如 Account.loadByAccountNumber() 调用 JDBC),不在序列图中暴露 Connection 或 PreparedStatement;
- 若需体现持久化,可用 > 标注作为被动参与者(如 database: MySQL),仅接收查询/更新消息,不主动返回。
最终,高质量的序列图是沟通的桥梁:对开发者,它厘清了对象职责边界;对业务方,它验证了流程是否符合真实 ATM 操作规范。坚持“领域驱动、场景聚焦、分层抽象”的三原则,你的 Swing 应用序列图将兼具专业性与实用性。











