基于MVC(Model-View-Controller)架构的小型应用程序。模拟一个简单的银行账户管理系统,包括账户模型、用户界面和控制器。
Model(模型)
// Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>
class Account {
private:
std::string accountNumber;
double balance;
public:
Account(const std::string& number, double initialBalance) : accountNumber(number), balance(initialBalance) {}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
bool withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
double getBalance() const {
return balance;
}
const std::string& getAccountNumber() const {
return accountNumber;
}
};
#endif // ACCOUNT_H
View(视图)
// AccountView.h
#ifndef ACCOUNTVIEW_H
#define ACCOUNTVIEW_H
#include "Account.h"
#include <iostream>
class AccountView {
public:
void displayAccountInfo(const Account& account) {
std::cout << "Account Number: " << account.getAccountNumber() << std::endl;
std::cout << "Balance: $" << account.getBalance() << std::endl;
}
void displayTransactionResult(bool success) {
if (success) {
std::cout << "Transaction successful." << std::endl;
} else {
std::cout << "Transaction failed." << std::endl;
}
}
};
#endif // ACCOUNTVIEW_H
Controller(控制器)
// AccountController.h
#ifndef ACCOUNTCONTROLLER_H
#define ACCOUNTCONTROLLER_H
#include "Account.h"
#include "AccountView.h"
class AccountController {
private:
Account account;
AccountView view;
public:
AccountController(const std::string& number, double initialBalance) : account(number, initialBalance), view() {}
void deposit(double amount) {
account.deposit(amount);
view.displayTransactionResult(true);
}
void withdraw(double amount) {
bool success = account.withdraw(amount);
view.displayTransactionResult(success);
}
void displayAccountInfo() {
view.displayAccountInfo(account);
}
};
#endif // ACCOUNTCONTROLLER_H
Main(主函数)
// main.cpp
#include "AccountController.h"
#include <iostream>
int main() {
// 创建一个账户
AccountController myAccount("123456789", 1000.0);
// 显示账户信息
myAccount.displayAccountInfo();
// 执行存款操作
std::cout << "Depositing $500..." << std::endl;
myAccount.deposit(500.0);
// 执行取款操作
std::cout << "Withdrawing $200..." << std::endl;
myAccount.withdraw(200.0);
// 再次显示账户信息
std::cout << "Account info after transactions:" << std::endl;
myAccount.displayAccountInfo();
return 0;
}