File tree Expand file tree Collapse file tree 5 files changed +80
-0
lines changed
patterns/proxy/conceptual Expand file tree Collapse file tree 5 files changed +80
-0
lines changed Original file line number Diff line number Diff line change 1+ # Proxy Pattern
2+ Proxy is a structural design pattern that lets you provide a substitute or placeholder for another
3+ object. A proxy controls access to the original object, allowing you to perform something either
4+ before or after the request gets through to the original object.
5+
6+ Tutorial: [ here] ( https://refactoring.guru/design-patterns/proxy ) .
7+
8+ ### Diagram:
9+ ![ image] ( https://user-images.githubusercontent.com/8049534/175924643-8d4f9ee4-80fc-4377-864c-d115a94a720c.png )
10+
11+ ### Client code:
12+ ``` dart
13+ void main() async {
14+ final subject = Proxy();
15+ print(subject.request()); // print "Proxy data"
16+
17+ print('Wait for 2 seconds...');
18+ await Future.delayed(Duration(seconds: 2));
19+
20+ print(subject.request()); // print "Real data"
21+ }
22+ ```
23+
24+ ### Output:
25+ ```
26+ Proxy data.
27+ Wait 2 seconds...
28+ Real data.
29+ ```
Original file line number Diff line number Diff line change 1+ import 'pattern/proxy.dart' ;
2+ import 'pattern/subject.dart' ;
3+
4+ void main () async {
5+ final subject = Proxy ();
6+ client (subject); // print "Proxy data"
7+
8+ print ('Wait 2 seconds...' );
9+ await Future .delayed (Duration (seconds: 2 ));
10+
11+ client (subject); // print "Real data"
12+ }
13+
14+ void client (Subject subject) {
15+ print (subject.request ());
16+ }
Original file line number Diff line number Diff line change 1+ import 'subject.dart' ;
2+ import 'real_subject.dart' ;
3+
4+ class Proxy implements Subject {
5+ @override
6+ String request () {
7+ if (isSubjectLoaded) {
8+ return _subject! .request ();
9+ }
10+
11+ _load ();
12+ return 'Proxy data.' ;
13+ }
14+
15+ bool get isSubjectLoaded => _subject != null ;
16+
17+ void _load () async {
18+ Future .delayed (Duration (seconds: 1 ), () {
19+ _subject = RealSubject ();
20+ });
21+ }
22+
23+ Subject ? _subject;
24+ }
Original file line number Diff line number Diff line change 1+ import 'subject.dart' ;
2+
3+ class RealSubject implements Subject {
4+ @override
5+ String request () {
6+ return 'Real data.' ;
7+ }
8+ }
Original file line number Diff line number Diff line change 1+ abstract class Subject {
2+ String request ();
3+ }
You can’t perform that action at this time.
0 commit comments