The Constructor Problem
class A {
private B _b;
public A() { _b = new B(); }
}
Dependency to the concrete class B
if B changes the constructor
A must change as well
if B becomes new dependencies, e.g. B(C, D),
A must create these dependencies as well
if C, D of B have their own dependencies, e.g. C(E), D
(F),
A must create them too...
A is a 'factory' of Bs
A influences the count created instances of type B
could be partially solved by the MonoState Pattern
ServiceLocator: temporary solution
class A {
private B _b;
public A(ServiceLocator locator) {
_b = locator.get(B.class);
}
}
ServiceLocator problems
extra dependency to the ServiceLocator
'push vs pull':we ask for a service, instead of just
getting the service
standard API across several libraries:
MyServiceLocator vs YourServiceLocator
but A needs *only* the services provided by B,
...
e.g. the interface IB
class A {
private IB _b;
public A(IB b) { _b = b; }
}
Classes as puzzle pieces
class A implements IA {
private IB _b;
public A(IB b) {
_b = b;
}
}
in -> required services: IB
out <- provided services: IA
IoC Container: puzzle table
Flavors
Required services declared/injected on
field
setter
constructor
method (e.g. init(...))
Wiring
automatic
manual: xml, JavaConfig, ...
References
Gilad Bracha:
Constructors Considered Harmful
Lethal Injection
Martin Fowler:
IoC Containers & DI
Guice
2 min. Pico
my delicious ioc
Pictures:
http://www.flickr.com/photos/joeyday/147651531/
http://www.flickr.com/photos/jowo/20840165/
http://commons.wikimedia.org/wiki/File:Iceberg_4_1997_08_07.jpg
0 comments
Post a comment