Advertisement
Guest User

Untitled

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