29 【行为型模式】状态模式

2018-01-21  本文已影响131人  猿笔记

解决的问题

  状态模式用于解决系统中复杂对象的状态转换以及不同状态下行为的封装问题。

定义

  状态模式(State Pattern):允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。其别名为状态对象(Objects for States),状态模式是一种对象行为型模式。

结构图


要素
● Context(环境类):环境类又称为上下文类,它是拥有多种状态的对象。由于环境类的状态存在多样性且在不同状态下对象的行为有所不同,因此将状态独立出去形成单独的状态类。在环境类中维护一个抽象状态类State的实例,这个实例定义当前状态,在具体实现时,它是一个State子类的对象。
● State(抽象状态类):它用于定义一个接口以封装与环境类的一个特定状态相关的行为,在抽象状态类中声明了各种不同状态对应的方法,而在其子类中实现类这些方法,由于不同状态下对象的行为可能不同,因此在不同子类中方法的实现可能存在不同,相同的方法可以写在抽象状态类中。
● ConcreteState(具体状态类):它是抽象状态类的子类,每一个子类实现一个与环境类的一个状态相关的行为,每一个具体状态类对应环境的一个具体状态,不同的具体状态类其行为有所不同。
abstract class State {  
    //声明抽象业务方法,不同的具体状态类可以不同的实现  
    public abstract void handle();  
} 

class ConcreteState extends State {  
    public void handle() {  
        //方法具体实现代码  
    }  
} 

class Context {  
    private State state; //维持一个对抽象状态对象的引用  
    private int value; //其他属性值,该属性值的变化可能会导致对象状态发生变化  
  
    //设置状态对象  
    public void setState(State state) {  
        this.state = state;  
    }  
  
    public void request() {  
        //其他代码  
        state.handle(); //调用状态对象的业务方法  
        //其他代码  
    }  
} 

说明:
  对象的状态转换的两种方式:

……  
     public void changeState() {  
    //判断属性值,根据属性值进行状态转换  
     if (value == 0) {  
        this.setState(new ConcreteStateA());  
    }  
    else if (value == 1) {  
        this.setState(new ConcreteStateB());  
    }  
       ......  
}  
   ……  
……  
     public void changeState(Context ctx) {  
    //根据环境对象中的属性值进行状态转换  
     if (ctx.getValue() == 1) {  
        ctx.setState(new ConcreteStateB());  
    }  
    else if (ctx.getValue() == 2) {  
        ctx.setState(new ConcreteStateC());  
    }  
       ......  
}  
   ……  

示例

  Sunny软件公司欲为某银行开发一套信用卡业务系统,银行账户(Account)是该系统的核心类之一,通过分析,Sunny软件公司开发人员发现在该系统中,账户存在三种状态,且在不同状态下账户存在不同的行为,具体说明如下:
(1) 如果账户中余额大于等于0,则账户的状态为正常状态(Normal State),此时用户既可以向该账户存款也可以从该账户取款;
(2) 如果账户中余额小于0,并且大于-2000,则账户的状态为透支状态(Overdraft State),此时用户既可以向该账户存款也可以从该账户取款,但需要按天计算利息;
(3) 如果账户中余额等于-2000,那么账户的状态为受限状态(Restricted State),此时用户只能向该账户存款,不能再从中取款,同时也将按天计算利息;
(4) 根据余额的不同,以上三种状态可发生相互转换。


class Account {  
    private String state; //状态  
    private int balance; //余额  
    ......  
      
    //存款操作    
    public void deposit() {  
        //存款  
        stateCheck();     
    }  
      
    //取款操作  
    public void withdraw() {  
        if (state.equalsIgnoreCase("NormalState") || state.equalsIgnoreCase("OverdraftState ")) {  
            //取款  
            stateCheck();  
        }  
        else {  
            //取款受限  
        }  
    }  
      
    //计算利息操作  
    public void computeInterest() {  
        if(state.equalsIgnoreCase("OverdraftState") || state.equalsIgnoreCase("RestrictedState ")) {  
            //计算利息  
        }  
    }  
      
    //状态检查和转换操作  
    public void stateCheck() {  
        if (balance >= 0) {  
            state = "NormalState";  
        }  
        else if (balance > -2000 && balance < 0) {  
            state = "OverdraftState";  
        }  
        else if (balance == -2000) {  
            state = "RestrictedState";  
        }  
        else if (balance < -2000) {  
            //操作受限  
        }  
    }  
    ......  
}  

存在的问题:

//银行账户:环境类  
class Account {  
    private AccountState state; //维持一个对抽象状态对象的引用  
    private String owner; //开户名  
    private double balance = 0; //账户余额  
      
    public Account(String owner,double init) {  
        this.owner = owner;  
        this.balance = balance;  
        this.state = new NormalState(this); //设置初始状态  
        System.out.println(this.owner + "开户,初始金额为" + init);   
        System.out.println("---------------------------------------------");      
    }  
      
    public double getBalance() {  
        return this.balance;  
    }  
      
    public void setBalance(double balance) {  
        this.balance = balance;  
    }  
      
    public void setState(AccountState state) {  
        this.state = state;  
    }  
      
    public void deposit(double amount) {  
        System.out.println(this.owner + "存款" + amount);  
        state.deposit(amount); //调用状态对象的deposit()方法  
        System.out.println("现在余额为"+ this.balance);  
        System.out.println("现在帐户状态为"+ this.state.getClass().getName());  
        System.out.println("---------------------------------------------");              
    }  
      
    public void withdraw(double amount) {  
        System.out.println(this.owner + "取款" + amount);  
        state.withdraw(amount); //调用状态对象的withdraw()方法  
        System.out.println("现在余额为"+ this.balance);  
        System.out.println("现在帐户状态为"+ this. state.getClass().getName());          
        System.out.println("---------------------------------------------");  
    }  
      
    public void computeInterest()  
    {  
        state.computeInterest(); //调用状态对象的computeInterest()方法  
    }  
}  
  
//抽象状态类  
abstract class AccountState {  
    protected Account acc;  
    public abstract void deposit(double amount);  
    public abstract void withdraw(double amount);  
    public abstract void computeInterest();  
    public abstract void stateCheck();  
}  
  
//正常状态:具体状态类  
class NormalState extends AccountState {  
    public NormalState(Account acc) {  
        this.acc = acc;  
    }  
  
public NormalState(AccountState state) {  
        this.acc = state.acc;  
    }  
          
    public void deposit(double amount) {  
        acc.setBalance(acc.getBalance() + amount);  
        stateCheck();  
    }  
      
    public void withdraw(double amount) {  
        acc.setBalance(acc.getBalance() - amount);  
        stateCheck();  
    }  
      
    public void computeInterest()  
    {  
        System.out.println("正常状态,无须支付利息!");  
    }  
      
    //状态转换  
    public void stateCheck() {  
        if (acc.getBalance() > -2000 && acc.getBalance() <= 0) {  
            acc.setState(new OverdraftState(this));  
        }  
        else if (acc.getBalance() == -2000) {  
            acc.setState(new RestrictedState(this));  
        }  
        else if (acc.getBalance() < -2000) {  
            System.out.println("操作受限!");  
        }     
    }     
}    
  
//透支状态:具体状态类  
class OverdraftState extends AccountState  
{  
    public OverdraftState(AccountState state) {  
        this.acc = state.acc;  
    }  
      
    public void deposit(double amount) {  
        acc.setBalance(acc.getBalance() + amount);  
        stateCheck();  
    }  
      
    public void withdraw(double amount) {  
        acc.setBalance(acc.getBalance() - amount);  
        stateCheck();  
    }  
      
    public void computeInterest() {  
        System.out.println("计算利息!");  
    }  
      
    //状态转换  
    public void stateCheck() {  
        if (acc.getBalance() > 0) {  
            acc.setState(new NormalState(this));  
        }  
        else if (acc.getBalance() == -2000) {  
            acc.setState(new RestrictedState(this));  
        }  
        else if (acc.getBalance() < -2000) {  
            System.out.println("操作受限!");  
        }  
    }  
}  
  
//受限状态:具体状态类  
class RestrictedState extends AccountState {  
    public RestrictedState(AccountState state) {  
        this.acc = state.acc;  
    }  
      
    public void deposit(double amount) {  
        acc.setBalance(acc.getBalance() + amount);  
        stateCheck();  
    }  
      
    public void withdraw(double amount) {  
        System.out.println("帐号受限,取款失败");  
    }  
      
    public void computeInterest() {  
        System.out.println("计算利息!");  
    }  
      
    //状态转换  
    public void stateCheck() {  
        if(acc.getBalance() > 0) {  
            acc.setState(new NormalState(this));  
        }  
        else if(acc.getBalance() > -2000) {  
            acc.setState(new OverdraftState(this));  
        }  
    }  
}  

class Client {  
    public static void main(String args[]) {  
        Account acc = new Account("段誉",0.0);  
        acc.deposit(1000);  
        acc.withdraw(2000);  
        acc.deposit(3000);  
        acc.withdraw(4000);  
        acc.withdraw(1000);  
        acc.computeInterest();  
    }  
}  

共享状态

  如果希望在系统中实现多个环境对象共享一个或多个状态对象,那么需要将这些状态对象定义为环境类的静态成员对象

class Switch {  
    private static State state,onState,offState; //定义三个静态的状态对象  
    private String name;  
      
    public Switch(String name) {  
        this.name = name;  
        onState = new OnState();  
        offState = new OffState();  
        this.state = onState;  
    }  
  
    public void setState(State state) {  
        this.state = state;  
    }  
  
    public static State getState(String type) {  
        if (type.equalsIgnoreCase("on")) {  
            return onState;  
        }  
        else {  
            return offState;  
        }  
    }  
          
    //打开开关  
    public void on() {  
        System.out.print(name);  
        state.on(this);  
    }  
      
//关闭开关  
    public void off() {  
        System.out.print(name);  
        state.off(this);  
    }  
}  

abstract class State {  
    public abstract void on(Switch s);  
    public abstract void off(Switch s);  
}  

//打开状态  
class OnState extends State {  
    public void on(Switch s) {  
        System.out.println("已经打开!");  
    }  
      
    public void off(Switch s) {  
        System.out.println("关闭!");  
        s.setState(Switch.getState("off"));  
    }  
}  
  
//关闭状态  
class OffState extends State {  
    public void on(Switch s) {  
        System.out.println("打开!");  
        s.setState(Switch.getState("on"));  
    }  
      
    public void off(Switch s) {  
        System.out.println("已经关闭!");  
    }  
}  

class Client {  
    public static void main(String args[]) {  
        Switch s1,s2;  
        s1=new Switch("开关1");  
        s2=new Switch("开关2");  
          
        s1.on();  
        s2.on();  
        s1.off();  
        s2.off();  
        s2.on();  
        s1.on();      
    }  
} 

使用环境类实现状态转换

  环境类作为一个状态管理器,统一实现各种状态之间的转换操作。

//屏幕类  
class Screen {  
    //枚举所有的状态,currentState表示当前状态  
    private State currentState, normalState, largerState, largestState;  
  
    public Screen() {  
        this.normalState = new NormalState(); //创建正常状态对象  
        this.largerState = new LargerState(); //创建二倍放大状态对象  
        this.largestState = new LargestState(); //创建四倍放大状态对象  
        this.currentState = normalState; //设置初始状态  
        this.currentState.display();  
    }  
      
    public void setState(State state) {  
        this.currentState = state;  
    }  
      
    //单击事件处理方法,封转了对状态类中业务方法的调用和状态的转换  
    public void onClick() {  
        if (this.currentState == normalState) {  
            this.setState(largerState);  
            this.currentState.display();  
        }  
        else if (this.currentState == largerState) {  
            this.setState(largestState);  
            this.currentState.display();  
        }  
        else if (this.currentState == largestState) {  
            this.setState(normalState);  
            this.currentState.display();  
        }  
    }  
}  
  
//抽象状态类  
abstract class State {  
    public abstract void display();  
}  
  
//正常状态类  
class NormalState extends State{  
    public void display() {  
        System.out.println("正常大小!");  
    }  
}  
  
//二倍状态类  
class LargerState extends State{  
    public void display() {  
        System.out.println("二倍大小!");  
    }  
}  
  
//四倍状态类  
class LargestState extends State{  
    public void display() {  
        System.out.println("四倍大小!");  
    }  
}  

class Client {  
    public static void main(String args[]) {  
        Screen screen = new Screen();  
        screen.onClick();  
        screen.onClick();  
        screen.onClick();  
    }  
}  

总结

适用场景

(1) 对象的行为依赖于它的状态(如某些属性值),状态的改变将导致行为的变化
(2) 在代码中包含大量与对象状态有关的条件语句,这些条件语句的出现,会导致代码的可维护性和灵活性变差,不能方便地增加和删除状态,并且导致客户类与类库之间的耦合增强

上一篇下一篇

猜你喜欢

热点阅读