Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Drawing;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
- using System.Reflection;
- using Gtk;
- using Utility;
- public class CachedFactory<K,T> : IDisposable where T : class
- {
- private Dictionary<K,T> m_Objects;
- private readonly Func<K,T> m_Initializer;
- private readonly Func<T,T> m_Disposer;
- public CachedFactory(Func<K,T> initializer, Func<T,T> disposer)
- {
- if(disposer == null && typeof(IDisposable).IsAssignableFrom(typeof(T)))
- {
- disposer = obj =>
- {
- if(obj != null)
- {
- ((IDisposable)obj).Dispose();
- }
- return null;
- };
- }
- m_Initializer = initializer;
- m_Disposer = disposer ?? (obj => null);
- }
- public T Create(K key)
- {
- T obj;
- if(m_Objects.TryGetValue(key, out obj))
- return obj;
- obj = m_Initializer(key);
- m_Objects[key] = obj;
- return obj;
- }
- public void Evict(K key)
- {
- m_Objects.Remove(key);
- }
- }
- public class BitmapCache : CachedFactory<string, Bitmap>
- {
- public BitmapCache()
- : base(LoadBitmap, DisposeBitmap)
- {
- }
- private Bitmap LoadBitmap(string resourceName)
- {
- using(Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
- {
- return new Bitmap(stream);
- }
- return null;
- }
- private Bitmap DisposeBitmap(Bitmap bitmap)
- {
- bitmap.Dispose();
- return null;
- }
- }
- /*
- * BitmapCache bc = new BitmapCache();
- * ... = bc.Create("foo.bmp"); // loaded
- * ... = bc.Create("foo.bmp"); // cached
- * bc.Evict("foo.bmp");
- * ... = bc.Create("foo.bmp"); // loaded again
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement