记录一次重构

重构前:

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,也可以加入到计算任务中来。

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

public class 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);
}
}

}


public interface IDXCacheItemWrapper
{
DXCacheKey Key {
get; set; }

object GetValue();
}

public class 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;
}

public object 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)
{
return default(T1);
}

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

  

yicone
-The future is worth fighting for.

posted on 2011-07-19 17:37 yicone 阅读(11) 评论(0) 编辑 收藏

发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 2110870 Vc+/PoP/lYg=

公告

[Bio]:碼農
主要生产工具是C#, 目前的工作領域是电子商务和第三方支付
上海张江

yUML Extension For VS2010

昵称:yicone
园龄:6年8个月
粉丝:2
关注:7

导航

搜索

 
 

常用链接

我的标签

随笔分类(50)

Friend

积分与排名

  • 积分 - 26058
  • 排名 - 4075

最新评论

推荐排行榜