Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.79 KB | None | 0 0
  1. using System;
  2. using System.Drawing;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Reflection;
  7.  
  8. public class CachedFactory<K,T> : IDisposable where T : class
  9. {
  10.     private Dictionary<K,T> m_Objects;
  11.     private readonly Func<K,T> m_Initializer;
  12.     private readonly Func<T,T> m_Disposer;
  13.    
  14.     public CachedFactory(Func<K,T> initializer, Func<T,T> disposer)
  15.     {
  16.         if(disposer == null && typeof(IDisposable).IsAssignableFrom(typeof(T)))
  17.         {
  18.             disposer = obj =>
  19.             {
  20.                 if(obj != null)
  21.                 {
  22.                     ((IDisposable)obj).Dispose();
  23.                 }
  24.                 return null;
  25.             };
  26.         }
  27.  
  28.         m_Initializer = initializer;
  29.         m_Disposer = disposer ?? (obj => null);
  30.     }
  31.    
  32.     public T Create(K key)
  33.     {
  34.         T obj;
  35.         if(m_Objects.TryGetValue(key, out obj))
  36.             return obj;
  37.        
  38.         obj = m_Initializer(key);
  39.         m_Objects[key] = obj;
  40.         return obj;
  41.     }
  42.    
  43.     public void Evict(K key)
  44.     {
  45.         m_Objects.Remove(key);
  46.     }
  47. }
  48.  
  49. public class BitmapCache : CachedFactory<string, Bitmap>
  50. {
  51.     public BitmapCache()
  52.         : base(LoadBitmap, null) // IDisposable objects will be automatically disposed.
  53.     {
  54.     }
  55.  
  56.     private Bitmap LoadBitmap(string resourceName)
  57.     {
  58.         using(Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
  59.         {
  60.             return new Bitmap(stream);
  61.         }
  62.        
  63.         return null;
  64.     }
  65. }
  66.  
  67.  
  68. /*
  69.  * BitmapCache bc = new BitmapCache();
  70.  * ... = bc.Create("foo.bmp"); // loaded
  71.  * ... = bc.Create("foo.bmp"); // cached
  72.  * bc.Evict("foo.bmp");
  73.  * ... = bc.Create("foo.bmp"); // loaded again
  74.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement