状态模式(重要):
对象行为型模式,系统中某个对象具有多个状态,这些状态之间可以相互转换,而且不同的状态具有不同的行为。将对象的状态从该对象中抽取出来作为状态类
状态模式的结构:拥有状态的对象类,抽象状态类,具体状态类
状态模式的适用场景:
1.对象在不同状态下具有不同的行为
2.代码中包含大量与对象状态有关的条件语句
状态模式的优点:
1.将状态之间的转换和不同状态下的行为封装在状态类中,提高了代码的可维护性
2.增加新的状态比较方便,只需改变对象的状态即可改变对象的行为
状态模式的缺点:
1.增加了系统中类和对象的个数
2.状态模式的结构和实现较为复杂
3.增加新的状态类和修改状态的行为需要修改源代码,对开闭原则的支持不太好
状态模式的例子:
拥有状态的对象类
public class Account {
private AccountState accountState;
private String owner;
private double balance;
public Account(String owner, double balanceInit) {
this.owner = owner;
this.balance = balanceInit;
this.accountState = new NormalState(this);
}
//存款
public void deposit(double amount) {
this.accountState.deposit(amount);
}
//取款
public void withdraw(double amount) {
this.accountState.withdraw(amount);
}
public void setState(AccountState accountState){
this.accountState = accountState;
}
public AccountState getState(){
return this.accountState;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
抽象状态类
public abstract class AccountState {
protected Account account;
public abstract void checkState();
public void deposit(double amount) {
this.account.setBalance(this.account.getBalance() + amount);
checkState();
}
public void withdraw(double amount) {
this.account.setBalance(this.account.getBalance() - amount);
checkState();
}
}
具体状态类
public class NormalState extends AccountState{
public NormalState(Account account) {
this.account = account;
}
public NormalState(AccountState accountState) {
this.account = accountState.account;
}
@Override
public void checkState() {
double balance = this.account.getBalance();
if (balance >= -2000 && balance <= 0) {
this.account.setState(new OverdraftState(this));
}else if(balance < -2000) {
this.account.setState(new RestrictedState(this));
}
}
}
public class OverdraftState extends AccountState{
public OverdraftState(AccountState accountState) {
this.account = accountState.account;
}
@Override
public void checkState() {
double balance = this.account.getBalance();
if (balance > 0) {
this.account.setState(new NormalState(this));
}else if (balance < -2000) {
this.account.setState(new RestrictedState(this));
}
}
}
public class RestrictedState extends AccountState{
public RestrictedState(AccountState accountState) {
this.account = accountState.account;
}
@Override
public void checkState() {
double balance = this.account.getBalance();
if (balance > 0) {
this.account.setState(new NormalState(this));
}else if (balance >= -2000 && balance <=0 ) {
this.account.setState(new OverdraftState(this));
}
}
}
测试类
public class Main {
public static void main(String[] args) {
Account account = new Account("xfg", 0);
account.deposit(5000);
System.out.println(account.getState());
account.withdraw(6000);
System.out.println(account.getState());
account.withdraw(2000);
System.out.println(account.getState());
}
}
状态模式的应用:
1.工作流和游戏软件中