今天完成软件设计实验二十二状态模式,以下为实验内容:
实验 22:状态模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解状态模式的动机,掌握该模式的结构;
2、能够利用状态模式解决实际问题。
[实验任务一]:银行账户
用Java代码模拟实现课堂上的“银行账户”的实例,要求编写客户端测试代码模拟用户存款和取款,注意账户对象状态和行为的变化。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
// 账户状态接口
interface AccountState {
void deposit(Account account, double amount);
void withdraw(Account account, double amount);
}
// 正常状态
class NormalState
implements AccountState {
public void deposit(Account account, double amount) {
account.setBalance(account.getBalance() + amount);
System.out.println("Deposited " + amount + ". Balance is " + account.getBalance());
}
public void withdraw(Account account, double amount) {
if (account.getBalance() >= amount) {
account.setBalance(account.getBalance() - amount);
System.out.println("Withdrew " + amount + ". Balance is " + account.getBalance());
} else {
System.out.println("Insufficient balance
for withdrawal");
}
}
}
// 透支保护状态
class OverdraftState
implements AccountState {
public void deposit(Account account, double amount) {
account.setBalance(account.getBalance() + amount);
System.out.println("Deposited " + amount + ". Balance is " + account.getBalance());
if (account.getBalance() > 0) {
account.setState(new NormalState());
}
}
public void withdraw(Account account, double amount) {
if (account.getBalance() + 100 >= amount) {
account.setBalance(account.getBalance() - amount);
System.out.println("Withdrew " + amount + ". Balance is " + account.getBalance());
} else {
System.out.println("Insufficient balance
for withdrawal");
}
}
}
// 冻结状态
class FrozenState
implements AccountState {
public void deposit(Account account, double amount) {
System.out.println("Account is frozen.
Deposit not allowed.");
}
public void withdraw(Account account, double amount) {
System.out.println("Account is frozen.
Withdrawal not allowed.");
}
}
// 账户类
class Account
{
private double balance;
private AccountState state;
public Account(double balance) {
this.balance = balance;
this.state = new NormalState();
}
public double getBalance() {
return balance;
}
public void setBalance(double balance)
{
this.balance = balance;
}
public AccountState getState() {
return state;
}
public void setState(AccountState state) {
this.state = state;
}
public void deposit(double amount)
{
state.deposit(this, amount);
}
public void withdraw(double amount)
{
state.withdraw(this, amount);
}
}
// 客户端测试代码
public class StatePatternTest {
public static void main(String[]
args) {
Account account = new Account(1000);
account.deposit(500);
account.withdraw(200);
account.withdraw(1500); // 触发透支保护
account.deposit(1000);
account.withdraw(500);