public class Girl { Kissable kissable; public Girl(Kissable kissable) { this.kissable = kissable; } public void kissSomeone() { kissable.kiss(this); } }
Assemble and use components just as before:
和前面一样去装配组件:
MutablePicoContainer pico = new DefaultPicoContainer();
pico.registerComponentImplementation(Boy.class);
pico.registerComponentImplementation(Girl.class);
现在运行:
Girl girl = (Girl) pico.getComponentInstance(Girl.class);
girl.kissSomeone();
The Girl will be given a Boy, because PicoContainer understands that it is a Kissable
Girl会自动接到一个Boy类型,因为微容器知道Boy是一个Kissable的对象
The Girl and the Boy no longer depend on each other, this is called the Dependency Inversion Principle since both components depend on the interface and no longer directly on each other.
Girl和Boy没有任何依赖关系,这就是Dependency Inversion Principle,也就是依赖接口而不直接存在依赖关系.
Use simple lifecycle
使用简单的生命周期控制
Change the Girl class to implement the simple default lifecycle and do it's kissing when the container is started.
改变Girl类,实现默认的生命周期控制类,并且是他在容器启动是就“kissing“
public class Girl implements Startable {
Kissable kissable;
public Girl(Kissable kissable) {
this.kissable = kissable;
}
public void start() {
kissable.kiss(this);
}
public void stop() {
}
}
Assemble container as before but instead of calling the Girl directly just start the container like this:
象以前一样装配容器,但是不需要直接调用Girl的方法,只需要启动容器即可:
pico.start();
This will instantiate all components that implement Startable and call the start method on each of them. To stop and dispose the container do as follows:
这个方法会调用所有实现了Startable的组件,并调用他们的start方法.停止他们就可以使用一下的方法了:
pico.stop();
pico.dispose();
Disposable API




