每日博客
状态模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解状态模式的动机,掌握该模式的结构;
2、能够利用状态模式解决实际问题。
[实验任务一]:银行账户
用Java代码模拟实现课堂上的“银行账户”的实例,要求编写客户端测试代码模拟用户存款和取款,注意账户对象状态和行为的变化。
C++版
#include<iostream>
using namespace std;
class Account;
class AccountState {
public:
Account *acc;
double balance;
public:
virtual void stateCheck() = 0;
void deposit(double amount);
virtual void withdraw(double amount);
};
class Account {
private:
AccountState *state;
string owner;
public:
Account(string owner, double init);
void setState(AccountState *state) {
this->state = state;
}
AccountState* getState() {
return this->state;
}
string getOwner() {
return this->owner;
}
void deposit(double amount) {
state->deposit(amount);
}
void withdraw(double amount) {
state->withdraw(amount);
}
};
class RedState :public AccountState {
public:
RedState(AccountState *state) {
this->balance = state->balance;
this->acc = state->acc;
}
void stateCheck();
};
class YellowState :public AccountState {
public:
YellowState(AccountState *state) {
this->balance = state->balance;
this->acc = state->acc;
}
void stateCheck();
};
class GreenState :public AccountState {
public:
GreenState(double balance, Account *acc) {
this->balance = balance;
this->acc = acc;
}
GreenState(AccountState *state) {
this->acc = state->acc;
this->balance = state->balance;
}
void stateCheck() {
if (balance >= -1000 && balance < 0) {
acc->setState(new YellowState(this));
}
else if (balance < -1000) {
acc->setState(new RedState(this));
}
else {
acc->setState(new GreenState(this));
}
}
};
void RedState::stateCheck() {
if (balance >= -1000 && balance < 0) {
acc->setState(new YellowState(this));
}
else if (balance < -1000) {
acc->setState(new RedState(this));
}
else {
acc->setState(new GreenState(this));
}
}
void YellowState::stateCheck() {
if (balance >= -1000 && balance < 0) {
acc->setState(new YellowState(this));
}
else if (balance < -1000) {
acc->setState(new RedState(this));
}
else {
acc->setState(new GreenState(this));
}
}
void AccountState::deposit(double amount) {
cout << "存款" << amount << endl;
this->balance += amount;
stateCheck();
cout << "账户余额:" << this->balance << endl;
}
void AccountState::withdraw(double amount) {
cout << "取款" << amount << endl;
if(amount> balance)cout << "您的账户余额不足,不能取款!" << endl;
else this->balance -= amount;
stateCheck();
cout << "账户余额:" << this->balance << endl;
}
Account::Account(string owner, double init) {
this->owner = owner;
this->state = new GreenState(init, this);
}
int main() {
Account *account = new Account("用户", 100);
account->deposit(100);
cout << "------------------------------" << endl;
account->withdraw(500);
cout << "------------------------------" << endl;
account->deposit(1000);
cout << "------------------------------" << endl;
account->withdraw(2000);
account->withdraw(100);
cout << "------------------------------" << endl;
account->deposit(2000);
cout << "------------------------------" << endl;
return 0;
}