lundi 1 mai 2017

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:

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 make two modifications.

  1. I want to instantiate 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).

  2. Currently I am concatenating the page + field to form a single value. I would like to update this design so that we have a single concurrent hashmap such as:

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

To request a new instance we would call something like:

pages.get(page).get(field).getInstance();

How could this be done?

Aucun commentaire:

Enregistrer un commentaire