1
+ // ignore_for_file: unused_field
2
+
1
3
class Service {}
2
4
3
5
class ExampleService implements Service {}
4
6
5
7
class AnotherExampleService implements Service {}
6
8
7
- /// Without dependency injection
9
+ /// ** Without dependency injection**
8
10
// the Client class contains a Service member variable initialized in the constructor.
9
11
// The client directly constructs and controls which service it uses,
10
12
// creating a hard-coded dependency.
11
13
12
14
class ClientWithoutDependencyInjection {
13
15
late Service _service;
14
16
17
+ /// The dependency is hard-coded.
15
18
ClientWithoutDependencyInjection () {
16
- // The dependency is hard-coded.
17
- _service = new ExampleService ();
19
+ _service = ExampleService ();
18
20
}
19
21
}
20
22
21
- /// Constructor injection
23
+ /// ** Constructor injection**
22
24
// most common form of dependency injection
23
25
// a class to request its dependencies through its constructor.
24
26
// This ensures the client is always in a valid state,
25
27
// since it cannot be instantiated without its necessary dependencies.
26
28
27
29
class ClientWithConstructorInjection {
28
- Service _service;
30
+ final Service _service;
29
31
30
32
// The dependency is injected through a constructor.
31
33
ClientWithConstructorInjection (this ._service);
32
34
}
33
35
34
- /// Setter injection
36
+ /// ** Setter injection**
35
37
// accepting dependencies through a setter method,
36
38
// rather than a constructor,
37
39
// clients can allow injectors to manipulate their dependencies at any time.
@@ -47,7 +49,7 @@ class ClientWithSetterInjection {
47
49
}
48
50
}
49
51
50
- /// Interface injection
52
+ /// ** Interface injection**
51
53
// dependencies are completely ignorant of their clients,
52
54
// yet still send and receive references to new clients.
53
55
@@ -80,16 +82,16 @@ class ClientWithInterfaceInjection implements ServiceSetter {
80
82
}
81
83
82
84
class ServiceInjector {
83
- Set <ServiceSetter > _clients = {};
85
+ final Set <ServiceSetter > _clients = {};
84
86
85
87
void inject (ServiceSetter client) {
86
88
_clients.add (client);
87
- client.setService (new ExampleService ());
89
+ client.setService (ExampleService ());
88
90
}
89
91
90
92
void switchAnotherExampleService () {
91
93
for (var client in _clients) {
92
- client.setService (new AnotherExampleService ());
94
+ client.setService (AnotherExampleService ());
93
95
}
94
96
}
95
97
}
0 commit comments