使用数据源的类应该通过接口访问它,并在构造时提供给类的正确实例.
首先,使DataSource成为一个接口:
public interface DataSource {
String getSomething();
}
现在具体实现:
public class B implements DataSource {
public String getSomething() {
//read a file, call a database whatever..
}
}
然后你的调用类看起来像这样:
public class MyThingThatNeedsData {
private DataSource ds;
public MyThingThatNeedsData(DataSource ds) {
this.ds = ds;
}
public doSomethingRequiringData() {
String something = ds.getSomething();
//do whatever with the data
}
}
您可以在代码中的其他位置实例化此类:
public class Program {
public static void main(String[] args) {
DataSource ds = new B(); //Here we've picked the concrete implementation
MyThingThatNeedsData thing = new MyThingThatNeedsData(ds); //And we pass it in
String result = thing.doSomethingThatRequiresData();
}
}
如果你想获得花哨的话,你可以使用像Spring或Guice这样的依赖注入框架来完成最后一步.
加分点:在您的单元测试中,您可以提供DataSource的模拟/存根实现,而您的客户端类将更加明智!