简体   繁体   English

抽象泛型类中的静态变量

[英]Static variable in an abstract generic class

I have a class called cache. 我有一个叫做缓存的类。 It is an generic, abstract class responsible for handling the global cache for forever type extends the class. 它是一个通用的抽象类,负责为永远的类型处理全局缓存扩展了该类。 My question is, if I have a static variable under the base class, will the static variable be unique per extending type or will it be the same for all types that extend Cache. 我的问题是,如果我在基类下有一个静态变量,则该静态变量在每个扩展类型中是唯一的,还是对于所有扩展Cache的类型而言都是相同的。

For example the interface: 例如界面:

Cache<K, V> 
  private static Cache<K, V>
  [creates a cache store on first load]
  static V get(K key);

Then I have an implementing class: 然后,我有一个实现类:

PersonCache extends Cache<String, Person>
   void load(String person);

JobCache extends Cache<Integer, Job>
   void load(Integer key);

Which behavior will be expected from Cache's static variable. 从Cache的静态变量可以预期哪种行为。 [The get variable's intention is to be a single public entry point to the JobCache/PersonCache's store] will each type (PersonCache, JobCache] have its own cache store, or will Cache try to store everything it receives? [get变量的意图是成为JobCache / PersonCache的存储的单个公共入口点]每个类型(PersonCache,JobCache)是否都有自己的缓存存储,还是Cache尝试存储收到的所有内容?

I don't think you can do that. 我认为您无法做到。 From the Java Language Specification Sec. 摘自Java语言规范部分。 8.1.2 : 8.1.2

It is a compile-time error to refer to a type parameter of a class C anywhere in the declaration of a static member of C or the declaration of a static member of any type declaration nested within C. It is a compile-time error to refer to a type parameter of a class C within a static initializer of C or any class nested within C. 在C的静态成员的声明或嵌套在C中的任何类型声明的静态成员的任何地方引用C类的类型参数是编译时错误。引用C的静态初始值设定项中的类C的类型参数或嵌套在C中的任何类。

The private static Cache variable will be stored once against the Cache class, and none of the sub-classes. private static Cache变量将针对Cache类存储一次 ,而不会存储任何子类。

The function of your [creates a cache store on first load] will have to decide which sub-class to instantiate. 您的[creates a cache store on first load]将必须确定要实例化的子类。 This method will be static so cannot be overridden. 此方法将是静态的,因此不能被覆盖。

If you're looking to implement the singleton pattern you should note that it's not really compatible with inheritance. 如果要实现单例模式 ,则应注意它与继承不是真正兼容的。 It also doesn't lend itself to a well tested system. 它还不适合测试良好的系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM