From 439a646b5edfde260d4b14821e6d7c18f819c7d7 Mon Sep 17 00:00:00 2001 From: Marko Živković Date: Tue, 3 Mar 2015 00:51:20 +0000 Subject: add ObjectCache for StorableObjects git-svn-id: https://svn.code.sf.net/p/xlogo4schools/svn/trunk@32 3b0d7934-f7ef-4143-9606-b51f2e2281fd --- logo/src/xlogo/storage/cache/ObjectCache.java | 91 +++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 logo/src/xlogo/storage/cache/ObjectCache.java (limited to 'logo') diff --git a/logo/src/xlogo/storage/cache/ObjectCache.java b/logo/src/xlogo/storage/cache/ObjectCache.java new file mode 100644 index 0000000..0fc6a30 --- /dev/null +++ b/logo/src/xlogo/storage/cache/ObjectCache.java @@ -0,0 +1,91 @@ +package xlogo.storage.cache; + +import java.io.File; +import java.util.HashMap; + +import xlogo.interfaces.Observable; +import xlogo.storage.StorableObject; + +/** + * Cache {@link StorableObject} based on {@link StorableObject#getFilePath()} + * @author Marko + * + */ +public class ObjectCache { + + /* + * Singleton + */ + + private static ObjectCache instance; + + public static final ObjectCache getInstance(){ + if(instance == null){ + instance = new ObjectCache(); + } + return instance; + } + + /* + * Cache fields + */ + + /** + * Class of T -> Map({@link StorableObject#getFilePath()} -> {@link StorableObject} of T) + */ + private HashMap,HashMap>> cache; + + private ObjectCache(){ + cache = new HashMap, HashMap>>(); + } + + /** + * Cache {@link StorableObject} based on {@link StorableObject#getFilePath()} + * @param storable + */ + public > void cache(StorableObject storable){ + if (storable == null || storable.get() == null){ + // TODO log warning + return; + } + Class c = storable.get().getClass(); + HashMap> classCache = cache.get(c); + if (classCache == null){ + classCache = new HashMap>(); + cache.put(c, classCache); + } + classCache.put(storable.getFilePath(), storable); + } + + /** + * + * @param file + * @param c + * @return + */ + @SuppressWarnings("unchecked") // implementation of cache guarantees that the cast succeeds + public ,E extends Enum> StorableObject get(File file, Class c){ + HashMap> classCache = cache.get(c); + if (classCache == null){ + return null; + } + return (StorableObject) classCache.get(file); + } + + public > void remove(StorableObject storable){ + if (storable == null || storable.get() == null){ + return; + } + Class c = storable.get().getClass(); + remove(storable.getFilePath(), c); + } + + public void remove(File file, Class c){ + HashMap> classCache = cache.get(c); + if (classCache == null){ + return; + } + classCache.remove(file); + } + +} -- cgit v1.2.3