状态模式:类的行为基于它的状态改变 属于行为型模式,创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。在代码中包含大量与对象状态有关的条件语句可以通过此模式将各种具体的状态类抽象出来
以图形状态 三角形、圆形、矩形为例:
- public interface State {
- void doAction(Shape shape);
-
- String toStr();
- }
- public class Shape {
-
- private State state;
-
- public State getState() {
- return state;
- }
-
- public void setState(State state) {
- this.state = state;
- }
- }
- public class TriangleState implements State{
- @Override
- public void doAction(Shape shape) {
- shape.setState(this);
- }
- @Override
- public String toStr(){
- return "三角形";
- }
- }
圆形状态 - public class CircularState implements State{
- @Override
- public void doAction(Shape shape) {
- shape.setState(this);
- }
- @Override
- public String toStr(){
- return "圆形";
- }
- }
矩形状态 - public class RectangleState implements State{
- @Override
- public void doAction(Shape shape) {
- shape.setState(this);
- }
- @Override
- public String toStr(){
- return "矩形";
- }
- }
- public static void main(String[] args) {
- Shape shape = new Shape();
- TriangleState triangleState = new TriangleState();
- triangleState.doAction(shape);
- String state = shape.getState().toStr();
- //三角形
- CircularState circularState = new CircularState();
- circularState.doAction(shape);
- state = shape.getState().toStr();
- //圆形
- RectangleState rectangleState = new RectangleState();
- rectangleState.doAction(shape);
- state = shape.getState().toStr();
- //矩形
- }