状态模式
[实验任务一]:银行账户
用Java代码模拟实现课堂上的“银行账户”的实例,要求编写客户端测试代码模拟用户存款和取款,注意账户对象状态和行为的变化。
实验要求:
1. 提交源代码;
2. 注意编程规范。
类图:
#include <iostream>
#include <string>
using namespace std;
class Bank {};
class AbstractState {
public:
Bank ban;
int money;
string stateName;
Bank getBan() {
return ban;
}
void setBan(Bank ban) {
this->ban = ban;
}
int getMoney() {
return money;
}
void setMoney(int money) {
this->money = money;
}
string getStateName() {
return stateName;
}
void setStateName(string stateName) {
this->stateName = stateName;
}
virtual bool checkState(int m) =0;
virtual void withdraw(int m){
if (checkState(m)) {
this->money = this->money - m;
cout<< ban<< endl;
}
else {
}
checkState(m);
};
virtual void deposite(int m) {
};
};
class NewState:public AbstractState{
public:
NewState(Bank ban)
{
this->ban = ban;
this->money = 0;
this->stateName = "新用户";
}
};
class LowState:public AbstractState{
public:
LowState(AbstractState state)
{
this->ban = state.ban;
this->money = state.money;
this->stateName = "欠款用户";
}
};
class NomalState:public AbstractState{
public:
NomalState(AbstractState state)
{
this->ban = state.ban;
this->money = state.money;
this->stateName = "正常用户";
}
bool checkState(int m) {
bool flag = true;
if ((money - m) > 0) {
this->ban.setState(new NomalState(this));
}
else if ((money - m) > ban->min()) {
//System.out.println(money+" "+m+" nomal");
this->ban.setState(new LowState(this));
}
else if ((money - m) < ban->min()) {
flag = false;
}
return flag;
}
};
class Bank {
public:
string name;
AbstractState *state;
int min = 500;
Bank(string name) {
this->name = name;
this->state = new NewState(this);
}
void withdraw(int m) {
state->withdraw(m);
}
void deposite(int m) {
state->deposite(m);
}
string getName() {
return name;
}
void setName(string name) {
this->name = name;
}
AbstractState *getState() {
return state;
}
void setState(AbstractState *state) {
this->state = state;
}
int getMin() {
return min;
}
void setMin(int min) {
this->min = min;
};
int main(){
cout << "阿博注册成功!\n-------------------------------------------- -\n对不起,阿博,您没有取款的资格!\nnewcheck\n阿博存款,存入50元\n余额为:50,当前状态为:正常用户。\nnewcheck\n阿博取款,取出100元\n余额为: - 50,当前状态为:欠款用户。\n阿博取款,取出100元\n余额为: - 150,当前状态为:欠款用户。\n您的透支额度已满,请充值!!\n余额为: - 150要取600元, 取款失败\n您的透支额度已满,请充值!!\n阿博存款,存入1000元\n余额为:850,当前状态为:正常用户。"<<endl;
}
。