Skip to content

Conversation

@ilopX
Copy link
Collaborator

@ilopX ilopX commented May 31, 2022

State Pattern

State is a behavioral design pattern that lets an object alter its behavior when its internal state
changes. It appears as if the object changed its class.

Tutorial: here.

Online demo:

Click on the picture to see the demo.

image

Video

video.mp4

Diagram:

image

Client code:

Change FreeState to MoveState:

class FreeState extends ManipulationState {
  @override
  void mouseDown(double x, double y) {
    tryToSelectAndStartMovingShape(x, y);
  }

  bool tryToSelectAndStartMovingShape(double x, double y) {
    final selectedShape = context.shapes.findShapeByCoordinates(x, y);

    context.changeState(
      MoveState(
        startX: x,
        startY: y,
        selectedShape: selectedShape,
      ),
    );

    return true;
  }
}

Change MoveState to ResizableState:

class MoveState extends SelectionState {
  @override
  void mouseMove(double x, double y) {
    selectedShape.move(x, y);
    context.update();
  }

  @override
  void mouseUp() {
    context.changeState(
      selectedShape.createSelectionState(),
    );
  }
}

Each shape has its own state manipulator:

class RectangleShape extends BaseShape {
  @override
  SelectionState createSelectionState() {
    return ResizableState(selectedShape: this);
  }
}

class CircleShape extends BaseShape {
  @override
  SelectionState createSelectionState() {
    return InnerRadiusState(selectedShape: this);
  }
}

@ilopX ilopX marked this pull request as ready for review June 2, 2022 22:04
@ilopX ilopX merged commit 8671918 into RefactoringGuru:main Jun 2, 2022
@ilopX ilopX deleted the add-manipulator-state branch June 2, 2022 22:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant