View RSS Feed

Hibernate

The Multiton pattern

Rate this Entry
by , 08-12-2011 at 04:39 AM (2965 Views)
The Multiton pattern is a pattern missing from ”the pattern bible”. It is extensive to dual layer (and beyond), but that is left for you to use intuitively when needed, it is not too difficult to do so.

The Multiton pattern is an extension of Singleton pattern.
Multiton lets you create and get any number of instances, they are distinguished by keys,
so if you want instance "a" it creates it for you the first time, and returned the created instance the next time, but if you then want "b", you get another instance.

Multiton can be used for example when creating a skin (from files) for a window. Maybe you refer to the same component (perhaps a menu item) in multiple files, and maybe those are not even predefined.


The following code is a template for Eclipse.
${enclosing_type} is your class.
${key_type} is the class used for keys.
${hash_table_type} is the class you want to use for the hash table, maybe java.util.HashMap.


Java Code:
/**
 * Multiton constructor
 * 
 * @param   key  The key
 */
private ${enclosing_type}(final ${key_type} key)
{
    super();
}

/**
 * Gets (and may set) instance by key
 * 
 * @param   key  The key
 * @return       The instance
 */
public static ${enclosing_type} getInstance(final ${key_type} key)
{
    synchronized (instances)
    {
        ${enclosing_type} instance;

        if ((instance = instances.get(key)) == null)
        {
            instance = new ${enclosing_type}(key);
            instances.put(key, instance);
        }

        return instance;
    }
}

/**
 * The instances
 */
private static final ${hash_table_type}<${key_type}, ${enclosing_type}> instances = new ${hash_table_type}<${key_type}, ${enclosing_type}>();

Submit "The Multiton pattern" to Facebook Submit "The Multiton pattern" to Digg Submit "The Multiton pattern" to del.icio.us Submit "The Multiton pattern" to StumbleUpon Submit "The Multiton pattern" to Google

Updated 08-12-2011 at 06:16 PM by Hibernate

Tags: None Add / Edit Tags
Categories
Patterns

Comments