67,515
社区成员
发帖
与我相关
我的任务
分享
interface IA {
void doSomething();
}
class PA {
//讨论使用注入和不使用注入的区别
IA a;
public void execute() {
a.doSomething(); //使用注入,代码可以很简洁,直接拿来就用,而且开发者不用关心 a 的生成细节
}
}
class AA implements IA {
public void doSomething() {
//do A business;
}
}
class AB implements IA {
public void doSomething() {
//do B business;
}
}
class PA {
IA a;
public void execute() {
//要根据不同需求自己生成a实例,怎么根据需求来分?假设用个配置文件properties
try {
String clz = System.getProperty("IA的实现类"); //A和B用户只需要配置properties文件
a = (IA) Class.forName(clz).getDeclaredConstructor().newInstance(new Object[] {"参数(假设有参数的话)"});
} catch (Exception e) {
e.printStackTrace();
}
a.doSomething();
}
}