实验?22:状态模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:?
1、理解状态模式的动机,掌握该模式的结构;
2、能够利用状态模式解决实际问题。
用Java代码模拟实现课堂上的“银行账户”的实例,要求编写客户端测试代码模拟用户存款和取款,注意账户对象状态和行为的变化。
public abstract class AccountState
{
protected Account acc;
protected double balance;
public AccountState(Account acc, double balance)
{
super();
this.acc = acc;
this.balance = balance;
}
//检查账户状态
public abstract void stateCheck();
//存款
public void deposit(double amount)
{
balance += amount;
System.out.println("存款成功");
System.out.println("当前余额为" + balance + "元");
}
//取款
public void withdraw(double amount)
{
if ((balance - amount) > -1000)
{
System.out.println("取钱成功!");
balance -= amount;
} else
{
System.out.println("余额不足!");
}
System.out.println("当前余额:" + balance + "元");
}
}
/**
* 余额大于等于0
* 绿色状态,正常状态,可存可取
*/
public class GreenState extends AccountState
{
public GreenState(Account acc, double balance)
{
super(acc, balance);
}
@Override
public void stateCheck()
{
if (balance < -1000)
{
acc.setState(new RedState(acc, balance));
} else if (balance < 0 && balance >= -1000)
{
acc.setState(new YellowState(acc, balance));
}
}
}
/**
* 余额小于-1000
* 红色状态,透支状态,只能存不能取
*/
public class RedState extends AccountState
{
public RedState(Account acc, double balance)
{
super(acc, balance);
}
@Override
public void stateCheck()
{
if (balance >= -1000 && balance < 0)
{
acc.setState(new YellowState(acc, balance));
} else if (balance >= 0)
{
acc.setState(new GreenState(acc, balance));
}
}
//不能取款
@Override
public void withdraw(double amount)
{
System.out.println("余额不足!");
System.out.println("当前余额:" + balance);
}
}
/**
* 余额小于0,并且大于等于-1000
* 黄色状态,欠费状态,可存可取
*/
public class YellowState extends AccountState
{
public YellowState(Account acc, double balance)
{
super(acc, balance);
}
@Override
public void stateCheck()
{
if (balance >= 0)
{
acc.setState(new GreenState(acc, balance));
} else if (balance < -1000)
{
acc.setState(new RedState(acc, balance));
}
}
}
/**
* 账户类
*/
public class Account
{
//账户状态
private AccountState state;
//账户所有人
private String owner;
public Account(String owner, double init)
{
this.owner = owner;
this.state = new GreenState(this, init);
this.state.stateCheck();
}
//设置状态
public void setState(AccountState amount)
{
this.state = amount;
}
//存款
public void deposit(double amount)
{
System.out.println(owner + "存" + amount + "元");
state.deposit(amount);
state.stateCheck();
}
//取款
public void withdraw(double amount)
{
System.out.println(owner + "取" + amount + "元");
state.withdraw(amount);
state.stateCheck();
}
}
public class Client
{
public static void main(String[] args)
{
//初始化账户名和账户余额
Account acc = new Account("账户:20213971 ", 200);
//存入1000
acc.deposit(1000);
//取800
acc.withdraw(800);
//取1000
acc.withdraw(1000);
//取1000
acc.withdraw(1000);
}
}