状态模式
银行账户
用Java代码模拟实现课堂上的“银行账户”的实例,要求编写客户端测试代码模拟用户存款和取款,注意账户对象状态和行为的变化。
package com.gazikel;
public class Account {
private AccountState state;
private String owner;
public Account(String owner, double init) {
this.owner = owner;
state = new GreenState(init, this);
System.out.println("账户:" + this.owner + ",余额:" + init);
}
public void setState(AccountState state) {
this.state = state;
}
public void deposit(double amount) {
state.deposit(amount);
System.out.println("现金余额为" + this.state.balance);
}
public void withdraw(double amount){
state.withdraw(amount);
System.out.println("现金余额为" + state.balance);
}
}
package com.gazikel;
public abstract class AccountState {
protected Account acc;
protected double balance;
public abstract void stateCheck();
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
}
package com.gazikel;
public class GreenState extends AccountState {
public GreenState() {}
public GreenState(double amount, Account account) {
balance = amount;
acc = account;
}
@Override
public void stateCheck() {
if (balance >= 0) {
acc.setState(new GreenState(balance, acc));
System.out.println("当前为正常(绿色)状态");
} else if(balance <0 && balance >= -1000) {
acc.setState(new YellowState(balance, acc));
System.out.println("当前为欠费(黄色)状态");
} else {
acc.setState(new RedState(balance, acc));
System.out.println("当前透支(红色)状态");
}
}
@Override
public void deposit(double amount) {
balance += amount;
System.out.println(balance);
stateCheck();
}
@Override
public void withdraw(double amount) {
balance -= amount;
stateCheck();
}
}
package com.gazikel;
public class RedState extends AccountState {
public RedState(double amount, Account acc) {
this.balance = amount;
this.acc = acc;
}
@Override
public void stateCheck() {
if (balance >= 0) {
acc.setState(new GreenState(balance, acc));
System.out.println("当前为正常(绿色)状态");
} else if(balance <0 && balance >= -1000) {
acc.setState(new YellowState(balance, acc));
System.out.println("当前为欠费(黄色)状态");
} else {
acc.setState(new RedState(balance, acc));
System.out.println("当前透支(红色)状态");
}
}
@Override
public void deposit(double amount) {
balance += amount;
stateCheck();
}
@Override
public void withdraw(double amount) {
System.out.println("透支状态,无法取款!");
}
}
package com.gazikel;
public class YellowState extends AccountState {
public YellowState(double amount, Account acc) {
this.balance = amount;
this.acc = acc;
}
@Override
public void stateCheck() {
if (balance >= 0) {
acc.setState(new GreenState(balance, acc));
System.out.println("当前为正常(绿色)状态");
} else if(balance <0 && balance >= -1000) {
acc.setState(new YellowState(balance, acc));
System.out.println("当前为欠费(黄色)状态");
} else {
acc.setState(new RedState(balance, acc));
System.out.println("当前透支(红色)状态");
}
}
@Override
public void deposit(double amount) {
balance += amount;
stateCheck();
}
@Override
public void withdraw(double amount) {
balance -= amount;
stateCheck();
}
}