বুধবার, ২০ নভেম্বর, ২০১৩

Identity Map



  • Ensure Kiv nq †h cÖwZwU object GKeviB gvÎ loaded n‡q‡Q|
  • GRb¨ cÖwZwU loaded object ‡K GKwU map Gi g‡a¨ ivLv nq|
  • hLb †Kvb object ‡K  refer Kiv nq ZLb Dnv‡K GB map Gi g‡a¨ †LuvRv nq  |
  •  hw` map Gi g‡a¨ cvIqv hvq Z‡e †mLvb †_‡K return Ki‡e bZzev database ‡_‡K object data load Ki‡e| AZtci D³ loaded data map G store Ki‡e| Then map ‡_‡K return Ki‡e|
  • Identity map use K‡i wb‡¤œv³ benefit mg~n cvIqv hvq-
    •  Resource consumption reduce K‡i| 
    •  Database Gi same object data Gi duplicate retrieval prevent Kivi Rb¨ Bnv context-specific, in-memory cache provide K‡i| d‡j performance improve nq| 

Example:
public abstract class Entity
{
        private readonly int _id;
       
        public int Id
        {
               get { return _id; }
        }
       
        internal Entity(int id)
        {
               _id = id;
        }
}
       
public sealed class Widget : Entity
{
        private static readonly EntityMap<Widget> _map = new EntityMap<Widget>(id => new Widget(id));
       
        public static EntityMap<Widget> Map
        {
               get { return _map; }
        }
       
        private Widget(int id) : base(id) { }
}
       
public sealed class Gadget : Entity
{
        private static readonly EntityMap<Gadget> _map = new EntityMap<Gadget>(id => new Gadget(id));
       
        public static EntityMap<Gadget> Map
        {
               get { return _map; }
        }
       
        private Gadget(int id) : base(id) { }
}
       
public class EntityMap<T> where T : Entity
{
        private readonly Dictionary<int, T> _entities = new Dictionary<int, T>();
        private readonly object _getLock = new object();
        private readonly Func<int, T> _entityGenerator;
       
        public T Get(int id)
        {
               lock (_getLock)
               {
                       T entity;
       
                       if (!_entities.TryGetValue(id, out entity))
                               _entities[id] = entity = _entityGenerator(id);
       
                       return entity;
               }
        }
       
        internal EntityMap(Func<int, T> entityGenerator)
        {
               _entityGenerator = entityGenerator;
        }
}
  • Client code G wb‡b¥v³fv‡e call Kiv n‡e-
// The following line results in a compilation error
// because Widget has no public constructors.
Widget badWidget = new Widget(1);
        
// Same for this one.
EntityMap<Widget> badWidgets = new EntityMap<Widget>();
        
// A Widget is properly retrieved like so...
Widget widget = Widget.Map.Get(1);



কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন