您可以使用延迟初始化。
在计算机编程中,延迟初始化是将对象的创建,值的计算或其他昂贵的过程延迟到第一次需要时才进行的策略。
这样就避免了时间耦合,这意味着您的类的使用者必须按特定的顺序调用特定的方法。必须start()
先调用是一种必须知道类在内部如何工作的方式,这很不好,因为您将来可能会更改它。
将昂贵的初始化延迟到第一次需要。
例:
public class FooClass{
private ExpensiveResource resource;
private CheapResource cheap;
public FooClass(String someParameter){
// constructor: initialize CheapResource cheap
// but NOT ExpensiveResource resource
}
public ExpensiveResource getExpensiveResource(){
if (resource == null) {
this.initializeExpensiveResource();
}
return this.resource
}
public String getExpensiveResourceName(){
if (resource == null) {
this.initializeExpensiveResource();
}
return this.resource.getName();
}
public CheapResource getCheapResource(){
return this.cheap;
}
private initializeExpensiveResource(){
// do expensive initialization of field "resource"
}
}
public class Test{
public static void main (String args[]){
FooClass foo = new FooClass("some string");
CheapResource cr = foo.getCheapResource();
String s = foo.getExpensiveResourceName();
// just now is the expensive resource initialized
}
}
start
和构造函数之间的区别?等等...