Skip to content

Commit fef151c

Browse files
committed
Impl conceptual proxy pattern.
1 parent 28e5cc0 commit fef151c

File tree

5 files changed

+80
-0
lines changed

5 files changed

+80
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
```
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import 'subject.dart';
2+
3+
class RealSubject implements Subject {
4+
@override
5+
String request() {
6+
return 'Real data.';
7+
}
8+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
abstract class Subject {
2+
String request();
3+
}

0 commit comments

Comments
 (0)