zoukankan      html  css  js  c++  java
  • 脚印:记录一次重构,将规则生产和规则消费(执行委托)分离

    重构前:

    Cache.Add(DXCacheKey.A, Register(DXCacheKey.A, DXCacheKeyType.A, dal.GetItemA, dal.GetItemAById)); Cache.Add(DXCacheKey.B, Register(DXCacheKey.B, DXCacheKeyType.B, dal.GetItemB, dal.GetItemBById));
    ...
    ...

    此次重构的目标是将规则的建立和使用进行分离(IDXCacheItemWrapper), 副产品是将某一形式的规则进行了封装(DXCacheItemWrapper)。

    分离的好处:

    一是,增强了代码的的可读性。因为这是个较为自然的过程,先创建规则,然后使用它。

    二是,其他形式的规则,只要符合IDXCacheItemWrapper,也可以加入到计算任务中来。

    三是,规则建立好后,不必立即使用,可以延迟计算。在此期间,可以对规则集进行筛选,增补等操作。

    publicclass Class1
    {
    public Class1()
    {
    DAL dal
    =new DAL();
    List
    <IDXCacheItemWrapper> list =new List<IDXCacheItemWrapper>
    {
    new DXCacheItemWrapper<ItemA, int>(DXCacheKey.A, DXCacheKeyType.A, dal.GetItemA, dal.GetItemAById),
    new DXCacheItemWrapper<ItemB, int>(DXCacheKey.B, DXCacheKeyType.B, dal.GetItemB, dal.GetItemBById),
    new DXCacheItemWrapper<ItemC, int>(DXCacheKey.C, DXCacheKeyType.C, dal.GetItemC, dal.GetItemCById),
    };

    foreach (IDXCacheItemWrapper w in list)
    {
    var value
    = w.GetValue();
    Cache.Add(w.Key.ToString(), value);
    }
    }

    }


    publicinterface IDXCacheItemWrapper
    {
    DXCacheKey Key {
    get; set; }

    object GetValue();
    }

    publicclass DXCacheItemWrapper<T1, T2> : IDXCacheItemWrapper
    {
    public DXCacheItemWrapper(DXCacheKey key, DXCacheKeyType keyType, Func<T1> getData1, Func<T2, T1> getData2)
    {
    Key
    = key;
    KeyType
    = keyType;
    GetData1
    = getData1;
    GetData2
    = getData2;
    }

    publicobject GetValue()
    {
    return GetValue<T1, T2>(Key, KeyType, GetData1, GetData2);
    }

    public T1 GetValue<T1, T2>(DXCacheKey key, DXCacheKeyType keyType, Func<T1> f1, Func<T2, T1> f2)
    {
    returndefault(T1);
    }

    public DXCacheKey Key { get; set; }
    public DXCacheKeyType KeyType { get; set; }
    public Func<T1> GetData1 { get; set; }
    public Func<T2, T1> GetData2 { get; set; }
    }

      

  • 相关阅读:
    Memcached 缓存服务器介绍
    hibernate ——联合主键
    hibernate ——关联关系
    Spring与Struts整合
    spring-DataSource
    hibernate ——helloWorld程序(annotation配置)
    hibernate ——helloWorld程序(XML配置)
    Struts2 知识体系
    Encoding filter 编码过滤器
    jQuery.ajax() 函数详解
  • 原文地址:https://www.cnblogs.com/yicone/p/2110870.html
Copyright © 2011-2022 走看看