-
Notifications
You must be signed in to change notification settings - Fork 1
/
decorator.dart
81 lines (65 loc) · 1.79 KB
/
decorator.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Base Interface for the Logger
abstract interface class Logger {
void log(String message);
}
// Basic Implementation
class BasicLogger implements Logger {
@override
void log(String message) {
print(message);
}
}
// Base class for decorators
abstract class LoggerDecorator implements Logger {
final Logger _wrappedLogger;
const LoggerDecorator(this._wrappedLogger);
@override
void log(String message) {
_wrappedLogger.log(message);
}
}
// Decorator for adding timestamps
class TimestampDecorator extends LoggerDecorator {
TimestampDecorator(Logger logger) : super(logger);
@override
void log(String message) {
final timestamp = DateTime.now().toIso8601String();
super.log('$timestamp: $message');
}
}
// Decorator for adding log levels
class LevelDecorator extends LoggerDecorator {
final String level;
LevelDecorator(Logger logger, this.level) : super(logger);
@override
void log(String message) {
super.log('[$level] $message');
}
}
// Decorator for writing to a file
class FileWriteDecorator extends LoggerDecorator {
final String filePath;
FileWriteDecorator(Logger logger, this.filePath) : super(logger);
@override
void log(String message) {
super.log(message);
// In a real implementation, we would write to a file here
print('Also writing "$message" to $filePath');
}
}
void main() {
// Create a basic logger
final basicLogger = BasicLogger();
// Create a decorated logger with multiple decorators
final decoratedLogger = FileWriteDecorator(
LevelDecorator(
TimestampDecorator(basicLogger),
'INFO'
),
'log.txt'
);
// Use the decorated logger
decoratedLogger.log('This is a test message');
// Use it again to show caching won't apply here
decoratedLogger.log('This is another test message');
}