//==============================================================================
// Registry.java
//==============================================================================
package sample.resource;
import java.util.Map;
import java.util.HashMap;
/**
* Responsibilities:
* - provides access to the registered resources.
*
*
* @author Copyright 2003 Nikolas S. Boyd.
*/
public class Registry {
/** Contains the registered resources. */
private Map contents;
/** Maintains the resource registry. */
private Registrar registrar;
/** Manages the resource backing store. */
private StorageManager manager;
/**
* Returns the resouce named (resourceName).
* @param resourceName identifies a registered resource.
* @return null if no such resource exists.
*/
public Resource
getResourceNamed(String resourceName) {
if (resourceName == null) return null;
return (Resource) this.contents.get(resourceName);
}
/**
* Returns the registered resource names.
*/
public String[]
getResourceNames() {
String[] empty = {};
return (String[]) this.contents.keySet().toArray(empty);
}
/**
* Stores the registered resources in the backing store.
*/
public void storeResources() {
this.manager.storeResources(this);
}
/**
* Constructs a new Registry.
*/
protected Registry() {
this.contents = this.createContents();
this.registrar = this.createRegistrar();
this.accept(this.createStorageManager());
this.registerShutdownHook();
}
/**
* Accepts the (storageManager) for resource loading.
* @param storageManager loads the configured resources.
*/
protected void
accept(StorageManager storageManager) {
this.manager = storageManager;
storageManager.loadResources(registrar);
}
/**
* Returns a new contents map.
*/
protected Map createContents() {
return new HashMap();
}
/**
* Returns a new registrar.
*/
protected Registrar createRegistrar() {
return new Registrar();
}
/**
* Returns a new storage manager.
*/
protected StorageManager createStorageManager() {
return new StorageManager();
}
/**
* Registers a shutdown hook.
*/
protected void registerShutdownHook() {
Runtime.getRuntime()
.addShutdownHook(this.createShutdownHook());
}
/**
* Returns a new shutdown hook.
*/
protected Thread createShutdownHook() {
return new Thread() {
public void run() {
manager.storeResources(Registry.this);
}
};
}
/**
* Responsibilities:
* - maintains the resource registry.
*
*
* @author Copyright 2003 Nikolas S. Boyd.
*/
protected class Registrar {
/**
* Registers the supplied (resource).
* @param resource identifies a resource to be registered.
*/
public void
register(Resource resource) {
contents.put(resource.getName(), resource);
}
} // Registrar
} // ResourceRegistry