Skip to content

Commit 80d2100

Browse files
committed
refactor: improve dependency injection examples and code style
1 parent b0d2bd4 commit 80d2100

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

more_important_patterns/dependency_injection/injection_types.dart

+12-10
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,39 @@
1+
// ignore_for_file: unused_field
2+
13
class Service {}
24

35
class ExampleService implements Service {}
46

57
class AnotherExampleService implements Service {}
68

7-
/// Without dependency injection
9+
/// **Without dependency injection**
810
// the Client class contains a Service member variable initialized in the constructor.
911
// The client directly constructs and controls which service it uses,
1012
// creating a hard-coded dependency.
1113

1214
class ClientWithoutDependencyInjection {
1315
late Service _service;
1416

17+
/// The dependency is hard-coded.
1518
ClientWithoutDependencyInjection() {
16-
// The dependency is hard-coded.
17-
_service = new ExampleService();
19+
_service = ExampleService();
1820
}
1921
}
2022

21-
/// Constructor injection
23+
/// **Constructor injection**
2224
// most common form of dependency injection
2325
// a class to request its dependencies through its constructor.
2426
// This ensures the client is always in a valid state,
2527
// since it cannot be instantiated without its necessary dependencies.
2628

2729
class ClientWithConstructorInjection {
28-
Service _service;
30+
final Service _service;
2931

3032
// The dependency is injected through a constructor.
3133
ClientWithConstructorInjection(this._service);
3234
}
3335

34-
/// Setter injection
36+
/// **Setter injection**
3537
// accepting dependencies through a setter method,
3638
// rather than a constructor,
3739
// clients can allow injectors to manipulate their dependencies at any time.
@@ -47,7 +49,7 @@ class ClientWithSetterInjection {
4749
}
4850
}
4951

50-
/// Interface injection
52+
/// **Interface injection**
5153
// dependencies are completely ignorant of their clients,
5254
// yet still send and receive references to new clients.
5355

@@ -80,16 +82,16 @@ class ClientWithInterfaceInjection implements ServiceSetter {
8082
}
8183

8284
class ServiceInjector {
83-
Set<ServiceSetter> _clients = {};
85+
final Set<ServiceSetter> _clients = {};
8486

8587
void inject(ServiceSetter client) {
8688
_clients.add(client);
87-
client.setService(new ExampleService());
89+
client.setService(ExampleService());
8890
}
8991

9092
void switchAnotherExampleService() {
9193
for (var client in _clients) {
92-
client.setService(new AnotherExampleService());
94+
client.setService(AnotherExampleService());
9395
}
9496
}
9597
}

0 commit comments

Comments
 (0)