|
| 1 | +# State Pattern |
| 2 | +State is a behavioral design pattern that lets an object alter its behavior when its internal state |
| 3 | +changes. It appears as if the object changed its class. |
| 4 | + |
| 5 | +Tutorial: [here](https://refactoring.guru/design-patterns/state). |
| 6 | + |
| 7 | +### Online demo: |
| 8 | +Click on the picture to see the [demo](https://RefactoringGuru.github.io/design-patterns-dart/#/state/manipulator_state). |
| 9 | + |
| 10 | +[](https://refactoringguru.github.io/design-patterns-dart/#/state/manipulator_state) |
| 11 | + |
| 12 | +### Video |
| 13 | +https://user-images.githubusercontent.com/8049534/171499203-1400c3ae-d5cd-4e48-a0b6-0252f4345d19.mp4 |
| 14 | + |
| 15 | +### Diagram: |
| 16 | + |
| 17 | + |
| 18 | +## Client code: |
| 19 | +### Change FreeState to MoveState: |
| 20 | +```dart |
| 21 | +class FreeState extends ManipulationState { |
| 22 | + @override |
| 23 | + void mouseDown(double x, double y) { |
| 24 | + tryToSelectAndStartMovingShape(x, y); |
| 25 | + } |
| 26 | +
|
| 27 | + bool tryToSelectAndStartMovingShape(double x, double y) { |
| 28 | + final selectedShape = context.shapes.findShapeByCoordinates(x, y); |
| 29 | +
|
| 30 | + context.changeState( |
| 31 | + MoveState( |
| 32 | + startX: x, |
| 33 | + startY: y, |
| 34 | + selectedShape: selectedShape, |
| 35 | + ), |
| 36 | + ); |
| 37 | +
|
| 38 | + return true; |
| 39 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +### Change MoveState to ResizableState: |
| 44 | +```dart |
| 45 | +class MoveState extends SelectionState { |
| 46 | + @override |
| 47 | + void mouseMove(double x, double y) { |
| 48 | + selectedShape.move(x, y); |
| 49 | + context.update(); |
| 50 | + } |
| 51 | +
|
| 52 | + @override |
| 53 | + void mouseUp() { |
| 54 | + context.changeState( |
| 55 | + selectedShape.createSelectionState(), |
| 56 | + ); |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +### Each shape has its own state manipulator: |
| 62 | +```dart |
| 63 | +class RectangleShape extends BaseShape { |
| 64 | + @override |
| 65 | + SelectionState createSelectionState() { |
| 66 | + return ResizableState(selectedShape: this); |
| 67 | + } |
| 68 | +} |
| 69 | +
|
| 70 | +class CircleShape extends BaseShape { |
| 71 | + @override |
| 72 | + SelectionState createSelectionState() { |
| 73 | + return InnerRadiusState(selectedShape: this); |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
0 commit comments