简体   繁体   English

您应该在Java中创建Generic Singleton类吗?

[英]Should you create a Generic Singleton class in java?

I am trying to create a CacheManager class for my cache in which I want to register an object of type Cache . 我正在尝试为要在其中注册Cache类型的对象的Cache创建CacheManager类。 My Cache can be generic and accepts two Key of type K and value of type V 我的缓存可以是通用的,可以接受两个K型密钥和V型值

EDIT after Stephen C comment 斯蒂芬·C评论后编辑

** I am creating the Cache as an in memory cache which will be used by a client as a library for caching particular objects. **我正在将Cache创建为内存中缓存,客户端将其用作缓存特定对象的库。 so one cache could contain only objects of Cache<Integer, Integer> while another might be like Cache<String, Integer> . 因此一个缓存只能包含Cache<Integer, Integer>对象,而另一个Cache<String, Integer>可能类似于Cache<String, Integer> The client should first register the cache with the CacheManager before being able to use it so that the CacheManager can manage the cache for the client and clean expired items etc. instead of having client do these things. 客户端应该先使用CacheManager注册缓存,然后才能使用它,以便CacheManager可以管理客户端的缓存并清除过期的项目等,而不是让客户端执行这些操作。 ** **

Cache.java Cache.java

public interface Cache<K,V> {
    public V get(K key);
    public void put(K key, V value);
    public K remove(K Key);
    public void clear();
}

Cache Manager.java 缓存管理器

public class CacheManager<K,V> {

    // Cannot make a static reference to the non-static type K,V
    private static final CacheManager<K,V> singletonInstance = new CacheManager<K,V>();
    private  Map<String, Cache<K,V>> map = new HashMap<>();

    private CacheManager() {}

    public static CacheManager<K,V> getSingletonInstance() {
        return singletonInstance;
    }


    public void addCache(Cache<K,V> cache) {
       //code goes here
    }
}

I want to create only a single instance of the CacheManager hence the idea for Singleton class and quite obviously it is giving the error of non static type K,V . 我只想创建CacheManager的单个实例,因此创建Singleton类的想法非常明显,它给出了非静态类型K,V的错误。 Is there a good way to do this? 有什么好方法吗?

You asked two separate questions - the first being " Should You create a Generic Singleton class..." and "Is there a good way to do this (create a Generic Singleton class)". 您问了两个单独的问题-第一个是“ 您是否应该创建通用Singleton类...”和“是否有很好的方法(创建Generic Singleton类)”。

To answer the first question, I would say no, do not attempt to create generic singleton classes, as making a class a singleton defeats the purpose of using generics. 要回答第一个问题,我会说不,不要尝试创建泛型单例类,因为将类设为单例会破坏使用泛型的目的。

By very nature, generics allows you to create a class that supports multiple types of data. 本质上,泛型允许您创建一个支持多种数据类型的类。 However, if it's a singleton, only one instance of the class is ever intended to be used, and therefore, you should already know the data-types you'll be using for the duration of the program. 但是,如果是单例,则仅打算使用该类的一个实例,因此,您应该已经知道在程序运行期间将使用的数据类型。

You cannot reference generic type parameters from a static context, as the static context is shared across all instance members of a class, which could include classes of various differing generic types. 您不能从静态上下文引用泛型类型参数,因为静态上下文在类的所有实例成员之间共享,该类可能包括各种不同泛型类型的类。

To answer your second question, alas, also no, there is no elegant way of doing this. 要回答您的第二个问题,可惜,也没有,没有优雅的方法可以做到这一点。 With additional context we may be able to suggest a better model to use to accomplish what you want. 通过附加的上下文,我们也许可以建议一个更好的模型来完成您想要的。

Update in response to your update 更新以响应您的更新

Your CacheManager object shouldn't need to know the generic type of the caches that it's managing, in order to do housekeeping tasks. 您的CacheManager对象无需执行其日常管理任务即可知道其管理的缓存的通用类型。 The CacheManager can simply be initilized as a singleton class without generic type parameters, such as: CacheManager可以简单地初始化为没有通用类型参数的单例类,例如:

public class CacheManager {

// No generic type information should be required.
private static final CacheManager singletonInstance = new CacheManager();
// This will allow a 'Cache' of any type to be registered.
private  Map<String, Cache> map = new HashMap<>();

The housekeeping and cache maintenance tasks shouldn't be concerned with the types of data that the client is keeping, but rather, you may have to create an additional data structure to support the time the client registered certain keys/values, and handle the removal of them. 管家和缓存维护任务不应该与客户端保留的数据类型有关,而是可能必须创建一个额外的数据结构来支持客户端注册某些键/值并处理删除操作的时间。其中。

To accomplish tracking the values that the client places in the Cache objects, perhaps you could simply include a map in the Cache class that maps the Key K to a long where you could store a timestamp for the last value update, then simply have the CacheManager query the cache object's keys for the last updated timestamp - this could even be iterated over with the entry set. 为了完成对客户端放置在Cache对象中的值的跟踪,也许您可​​以在Cache类中简单地包含一个映射,该映射将Key K映射到一个long ,您可以在其中存储上一次值更新的时间戳,然后只需使用CacheManager查询缓存对象的键以获取最新的时间戳-甚至可以使用条目集对其进行迭代。

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

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