状态模式

2019-05-07  本文已影响0人  Davisxy

核心

结构:

小栗子

package com.principle.state;

public interface State {
    void handle();

}
package com.principle.state;

public class FreeState implements State{

    @Override
    public void handle() {
        System.out.println("空闲状态,没人居住!!!");
    }

}
package com.principle.state;

public class BookedState implements State{

    @Override
    public void handle() {
        System.out.println("房间已预订,别人不能定!");
    }

}
package com.principle.state;

public class CheckedState implements State{

    @Override
    public void handle() {
        System.out.println("房间已入住,请勿打扰!");
    }

}
package com.principle.state;

/**
 * 维持不同状态的切换
 * @author xy
 *
 */
public class Context {
    public State state;

    public void setState(State state) {
        System.out.println("修改状态!");
        this.state = state;
        state.handle();
    }
    
    
}
package com.principle.state;

public class Client {
    public static void main(String[] args) {
        Context context=new Context();
        context.setState(new FreeState());
        context.setState(new BookedState());
    }
}
结果打印:
修改状态!
空闲状态,没人居住!!!
修改状态!
房间已预订,别人不能定!

类图

状态模式.png
上一篇下一篇

猜你喜欢

热点阅读