经过提取Dependency后,Hello World基本组成:
三个接口类:
1 MyDestination:即输出到哪里
public interface MyDestination {
void write(String string);
}
2 StringProvider:提供输出内容
public interface StringProvider {
String get();
}
3 MyApplet:main方法中的启动类
public interface MyApplet extends Runnable {
void run();
}
整体代码:
//主类
public class App {
public static void main(String[] args) {
MyApplet mainApplet= Configuration.getMainApplet();
mainApplet.run();
}
}
//Configuration类
public class Configuration {
public static MyApplet getMainApplet(){
return new StringWritingApplet(
new PrintStreamWriter(System.out),
new StringProvider() {
@Override
public String get() {
return "Hello World";
}
}
);
}
}
//StringWritingApplet类
public class StringWritingApplet implements MyApplet {
private MyDestination myDestination;
private StringProvider stringProvider;
public StringWritingApplet(MyDestination myDestination,StringProvider stringProvider) {
this.myDestination = myDestination;
this.stringProvider= stringProvider;
}
private void writeString() {
myDestination.write(stringProvider.get());
}
public void run() {
writeString();
}
}
//PrintStreamWriter类
public class PrintStreamWriter implements MyDestination {
private PrintStream out;
public PrintStreamWriter(PrintStream out) {
this.out = out;
}
@Override
public void write(String string) {
out.println(string);
}
}
使用Guice优化:
<1> 在PrintStreamWriter、StringWritingApplet 构造函数上加上@Inject注解,
表示构造参数是由guice提供的
<2> "告诉"guice给上面两个函数什么构造参数,
定义MainModule并继承guice中的AbstractModule类,重写configure()方法:
public class MainModule extends AbstractModule {
@Override
protected void configure() {
bind(MyApplet.class).to(StringWritingApplet.class);
bind(MyDestination.class).to(PrintStreamWriter.class);
bind(PrintStream.class).toInstance(System.out);
}
@Provides private String getString(){
return "Hello World";
}
}
configure方法中:
bind(MyApplet)表示将MyApplet接口绑定到StringWritingApplet实现类上;
bind(MyDestination.class)表示将StringWritingApplet构造参数1绑定到PrintStreamWriter类上;
第三个bind,是将PrintStreamWriter构造参数PrintStream绑定对应实例System.out
@provides表示将StringWritingApplet中的另一个参数与guice自带的Provider类绑定
image.png
如果说不想在MainModule中实现复杂的事情,需要再定义一个Module类,在MainModule中只需要install下即可
public class MainModule extends AbstractModule {
@Override
protected void configure() {
install(new HelloWorldModule());
}
}
public class HelloWorldModule extends AbstractModule {
@Override
protected void configure() {
bind(MyApplet.class).to(StringWritingApplet.class);
bind(MyDestination.class).to(PrintStreamWriter.class);
bind(PrintStream.class).toInstance(System.out);
}
@Provides
private String getString(){
return "Hello World";
}
}
这里绑定“hello,world”有多种实现方法:
还可以在StringWritingApplet的构造函数上,
注意加了自定义注解@Output
image.png
在module中:
image.png
这样也能实现将String绑定为“Hello World”
网友评论