設計一個基於 Java 的 ATM 系統是經典的面向對象編程練習。本文提供完整的設計思路、核心類結構、界面實現方案及關鍵技術點,幫助初學者快速構建功能完整的銀行自動取款機模擬系統。
// 賬戶接口
interface Account {
double getBalance();
boolean deposit(double amount);
boolean withdraw(double amount);
boolean transfer(Account target, double amount);
}
// 基礎賬戶實現
class BankAccount implements Account {
private String accountId;
private String password;
private double balance;
private List transactions;
// 封裝屬性,提供業務方法
}
// 異常處理
class InsufficientFundsException extends Exception { ... }
class InvalidAccountException extends Exception { ... }
interface BankService {
Account login(String id, String password);
void logout(Account account);
List getHistory(Account account);
}
class BankServiceImpl implements BankService {
private Map accounts = new HashMap<>();
// 實現業務邏輯,處理事務、持久化
}
LoginFrame:登錄界面,驗證賬號密碼MainFrame:主菜單,四大功能按鈕DepositDialog、WithdrawDialog、TransferDialog、BalanceDialog:各功能對話框CardLayout 或 JTabbedPane 管理界面切換轉賬操作必須保證原子性:
public boolean transfer(Account from, Account to, double amount) {
synchronized(from) {
synchronized(to) {
if (from.withdraw(amount)) {
if (to.deposit(amount)) {
// 記錄雙方交易流水
return true;
} else {
from.deposit(amount); // 回滾
}
}
return false;
}
}
}
Account 對象到文件accounts(id, password, balance), transactions(id, from_id, to_id, amount, time, type)遵循 MVC 模式:
Account, TransactionBankService如最佳回答所述,尚硅谷免費視頻中的 bank 項目是極佳參考,涵蓋 JDBC、事務、Swing 界面等完整技術棧。