File tree Expand file tree Collapse file tree 5 files changed +108
-0
lines changed
patterns/command/conceptul Expand file tree Collapse file tree 5 files changed +108
-0
lines changed Original file line number Diff line number Diff line change 1+ import '../pattern/command.dart' ;
2+ import '../mut_str/mut_str.dart' ;
3+
4+ class AddTextCommand implements Command {
5+ final String addedText;
6+ final MutStr mutStr;
7+
8+ AddTextCommand (this .addedText, this .mutStr);
9+
10+ @override
11+ void execute () {
12+ additionPosition = mutStr.len;
13+ mutStr.push (addedText);
14+ }
15+
16+ @override
17+ void undo () {
18+ if (additionPosition == null ) {
19+ return ;
20+ }
21+
22+ mutStr.delete (additionPosition! , additionPosition! + addedText.length);
23+ }
24+
25+ int ? additionPosition;
26+ }
Original file line number Diff line number Diff line change 1+ import '../pattern/command.dart' ;
2+ import '../mut_str/mut_str.dart' ;
3+
4+ class InsertTextCommand extends Command {
5+ final int pos;
6+ final String insertText;
7+ final MutStr mutStr;
8+
9+ InsertTextCommand (this .insertText, this .mutStr, {required this .pos});
10+
11+ @override
12+ void execute () {
13+ _isNotExecute = false ;
14+ mutStr.insert (pos + 1 , insertText);
15+ }
16+
17+ @override
18+ void undo () {
19+ if (_isNotExecute) {
20+ return ;
21+ }
22+
23+ mutStr.delete (pos + 1 , insertText.length - 1 );
24+ }
25+
26+ bool _isNotExecute = true ;
27+ }
Original file line number Diff line number Diff line change 1+ import 'mut_str/mut_str.dart' ;
2+ import 'command/add_text_command.dart' ;
3+ import 'command/insert_text_command.dart' ;
4+
5+ void main () {
6+ final mutStr = MutStr ();
7+
8+ final input1 = AddTextCommand ('One' , mutStr);
9+ final input2 = AddTextCommand ('Three' , mutStr);
10+ final input3 = InsertTextCommand (' Two ' , mutStr, pos: 2 );
11+
12+ input1.execute ();
13+ print ('text = $mutStr ' ); // mutStr = "One"
14+
15+ input2.execute ();
16+ print ('text = $mutStr ' ); // mutStr = "OneThree"
17+
18+ input3.execute ();
19+ print ('text = $mutStr ' ); // mutStr = "One Two Three"
20+
21+ input3.undo ();
22+ print ('text = $mutStr ' ); // mutStr = "OneThree"
23+
24+ input2.undo ();
25+ print ('text = $mutStr ' ); // mutStr = "One "
26+
27+ input1.undo ();
28+ print ('text = $mutStr ' ); // mutStr = ""
29+ }
Original file line number Diff line number Diff line change 1+ class MutStr {
2+ void push (String str) {
3+ _buff.addAll (str.split ('' ));
4+ }
5+
6+ void insert (int pos, String str) {
7+ _buff.insert (pos, str);
8+ }
9+
10+ void delete (int startPos, int len) {
11+ _buff.removeRange (startPos, len);
12+ }
13+
14+ int get len => _buff.length;
15+
16+ @override
17+ String toString () {
18+ return _buff.join ('' );
19+ }
20+
21+ final _buff = < String > [];
22+ }
Original file line number Diff line number Diff line change 1+ abstract class Command {
2+ void execute ();
3+ void undo ();
4+ }
You can’t perform that action at this time.
0 commit comments