我想知道类初始化的最佳实践是什么,
我的意思是我应该在顶层初始化一个类一次 Customer c = new Customer();
,并在类中的任何地方使用它:
Tools tools = new Tools();
public boolean doCIdCheck(int cId) {
final Iterator<Customer> cursor = tools.Customers.iterator();
while (cursor.hasNext()) {
if (cursor.next().getCIdCheck(cId)) {
return true;
}
}
return false;
}
或者我应该在需要的地方使用new Customer().checkCId();
:
public boolean doCIdCheck(int cId) {
final Iterator<Customer> cursor = new Tools().Customers.iterator();
while (cursor.hasNext()) {
if (cursor.next().getCIdCheck(cId)) {
return true;
}
}
return false;
}
或者最好让每个函数/方法都有自己的类实例:
public boolean doCIdCheck(int cId) {
Tools tools = new Tools();
final Iterator<Customer> cursor = tools.Customers.iterator();
while (cursor.hasNext()) {
if (cursor.next().getCIdCheck(cId)) {
return true;
}
}
return false;
}
最佳答案
从您的示例来看,最好的方法是将 Tools
的共享方法和成员声明为 static
而不是创建实例,然后将它们调用为
final Iterator<Customer> cursor = Tools.Customers.iterator();
这当然假设您不在Tools
中存储可能导致冲突的数据,在这种情况下,最好创建多个实例。
关于Java 对象在一个类中初始化多次还是只初始化一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258990/