Skip to content

Commit 2dde104

Browse files
committed
Add README.
1 parent c42aadf commit 2dde104

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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+
[![image](https://user-images.githubusercontent.com/8049534/171070341-1decb58f-033b-4eb5-89d4-355aafa6b680.png)](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+
![image](https://user-images.githubusercontent.com/8049534/171740942-659d3ec9-8355-4078-a7d6-b4a338b41187.png)
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

Comments
 (0)