简体   繁体   English

基于经过时间的单例(或多例)模式

[英]Singleton (or Multiton) Pattern Based on Elapsed Time

Below I've implemented the Multiton pattern but I think this question applies equally to the Singleton pattern: 下面,我实现了Multiton模式,但我认为这个问题同样适用于Singleton模式:

private static ConcurrentHashMap<String, LocatorDAO> instances = new   ConcurrentHashMap<String, LocatorDAO>();

public static LocatorDAO getInstance(String page String field) 
{
    String instanceID = page + " " + field; 
    LocatorDAO result = instances.get(instanceID);

    if (result == null) 
    {

        LocatorDAO m = new LocatorDAO(page, field);
        result = instances.putIfAbsent(instanceID, m);

        if (result == null)
            result = m;
    }

    return result;
}

I would like to modify this design by instantiating a new instance every 300 seconds - so if 300 seconds passed from the time we instantiated the previous instance I would like to instantiate it again (or if the instance was never instantiated). 我想通过每300秒实例化一个新实例来修改这种设计-因此,如果从实例化前一个实例的时间起经过了300秒,我想再次实例化它(或者如果实例从未实例化)。

How could this be done? 怎么办呢?

The solution: Save the timestamp whenever an instance is created. 解决方案:创建实例时保存时间戳。 Whenever a new instance is created, check the saved timestamp and find the time difference. 每当创建新实例时,请检查保存的时间戳并找到时差。

How to implement: There are at least two ways that you can achieve this: 实施方法:至少有两种方法可以实现:

  1. Add the creation timestamp to instanceID and search through all the keys manually. 将创建时间戳记添加到instanceID并手动搜索所有键。 This is a simple solution but will be slower because you'll have to search through all the keys in your hash map. 这是一个简单的解决方案,但会变慢,因为您必须在哈希映射中搜索所有键。

  2. Implement a bean class that will have two fields LocatorDAO and a long field to save the creation time. 实现一个bean类,它将具有两个字段LocatorDAO和一个长字段以节省创建时间。 During creation, if there is an item in the hash map, check it's creation time and if it is older than 300 seconds, create a new instance 在创建过程中,如果哈希图中有一个项目,请检查它的创建时间,如果它早于300秒,则创建一个新实例

Hope this answer (without code examples) is good enough. 希望这个答案(没有代码示例)足够好。

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

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