MorphicFactory.java

package edu.udel.cis.vsl.tass.morph;

import java.util.HashMap;
import java.util.Set;

/**
 * A simple implemntation of MorphicFactoryIF, using a HashMap to store the
 * canonical components. This class should is intended to be extended.
 */
public abstract class MorphicFactory<T extends Morphic> implements
		MorphicFactoryIF<T> {

	private HashMap<T, T> map = new HashMap<T, T>();

	@Override
	public T canonic(T component) {
		if (component.isCanonic())
			return component;
		component.commit();

		T result = map.get(component);

		// the map.get should result in the hashCode of the component
		// being computed and cached, and ditto for all of its children

		if (result == null) {
			((MorphicObject) component).canonicalize();
			map.put(component, component);
			canonicalizeChildren(component);
			return component;
		} else {
			return result;
		}
	}

	/**
	 * Modifies the component by replacing the children (component fields) with
	 * canonical representatives.
	 */
	protected abstract void canonicalizeChildren(T component);

	/**
	 * The total number of canonical components maintained by this factory.
	 */
	public int numStored() {
		return map.size();
	}

	/** Returns the set of canonical components stored by this factory */
	@Override
	public Set<T> store() {
		return map.keySet();
	}
}