如何在JAVA类中构造以下需求
场景如下:如何在JAVA类中构造以下需求,java,Java,场景如下: 数据库“overAllCount”中有一个字段,其中包含一些值 我在设计的许多类中都必须使用这个变量 我想在一个类中获取这个'overAllCount',比如'OverAllCountClass',并在其类名为OverAllCountClass.overAllCount的所有子类中使用它。基本上就像一个静态变量 我该怎么做? 我的解决办法是: public Class OverAllCountClass { public static int OverAllCount;
我的解决办法是:
public Class OverAllCountClass {
public static int OverAllCount;
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
}
//////////像这样使用它//////////////
public class Usecount {
public void abc(){
// BUT IT IS NOT POSSIBLE becuase OverAllCountClass is not yet initialize
int mycount = OverAllCountClass.overAllCount
}
}
如何实现这一点?如果您关心的是,静态变量
overAllCount
可能无法初始化,如果您希望在首次调用类OverAllCountClass
时初始化它,则可以使用
第一次加载类时调用静态初始值设定项块。当JVM看到它被使用时,类首先被加载
public class Usecount {
public void abc(){
//When JVM sees that OberAllCountClass is used here, it executes the static block of OverAllCountClass and by the time below statement is executed, overAllCount is initialized
int mycount = OverAllCountClass.overAllCount
}
}
不需要在这里使用静态
。使用getter获取计数,而不是使用公共静态变量,该变量可以被其他类修改/滥用。我将提供一个特定的API,它可以隐藏实现,并在需要时执行延迟加载等操作:
public static final Value getValue(){
//evaluate private field
return value;
}
此API可以是静态方法,也可以是单例范围的方法,具体取决于用例。另一个选项是使
总体CountClass
a
这样做的好处是,对于访问
OverAllCountClass
的代码,无论它是否为单例,都是透明的。这使得替换实现更容易。您能解释一下吗?谢谢@Sanbhat:我想这就是我想要的使用静态初始化块来初始化静态属性。静态块在类加载期间只运行一次。。。。所以不需要再次从数据库中获取值again@RakeshSoni:谢谢拉凯什。我想这就是我想要的。
public Class OverAllCountClass {
protected int overAllCount; //will allow you to use in subclass too
public OverAllCountClass(){
// Fetch overAllCount from database here and set its value
}
public int getOverAllCount(){
return overAllCount;
}
}
public class Usecount {
//pass the instance of overAllCountInstance to UseCount somehow using constructor or setter
private OverAllCountClass overAllCountInstance;
public void abc(){
int mycount = overAllCountInstance.getOverAllCount();
}
}
public static final Value getValue(){
//evaluate private field
return value;
}
public class OverAllCountClass {
private static final OverAllCountClass instance = new OverAllCountClass();
private Integer overAllCount = null;
// make it non-instanciable outside by making the constructor private
private OverAllCountClass {
}
public static OverAllCountClass getInstance() {
return instance;
}
public int getOverAllCount() {
if (overAllCount = null) {
//get value from database and assign it
}
return overAllCount;
}
}