2

场景是这样的:

  1. 数据库“overAllCount”中有一个包含一些值的字段。
  2. 我必须在我设计的许多类中使用这个变量。
  3. 我想在一个类中获取这个“overAllCount”,比如“OverAllCountClass”,并在其类名(如 OverAllCountClass.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

      }
}

我怎样才能做到这一点?

4

4 回答 4

2

如果您担心的是,静态变量overAllCount可能不会被初始化,并且如果您希望它在类OverAllCountClass第一次被调用时被初始化,那么您可以使用静态初始化程序块

public class OverAllCountClass {

    public static int overAllCount;

    static {
        overAllCount = fetchOverAllCount();
    }
 }

首次加载类时调用静态初始化程序块。当 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
     }
}
于 2013-09-03T07:09:22.997 回答
0
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();

      }
}

这里不用static。使用 getter 获取计数

于 2013-09-03T07:10:21.263 回答
0

而不是拥有一个可以被其他类修改/滥用的公共静态变量。我会提供一个特定的 API,它可以隐藏实现并在需要时执行延迟加载等操作:

public static final Value getValue(){
//evaluate private field
return value;
}

此 API 可以是静态方法,也可以是单例范围的方法,具体取决于用例。

于 2013-09-03T07:11:55.773 回答
0

OverAllCountClass另一种选择是制作Singleton

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;
    }
}

这样做的好处是访问OverAllCountClass它的代码是透明的,无论它是否是单例。这使得换出实现更容易。

于 2013-09-03T07:22:22.910 回答