代码之美~利用构造方法实现模块的解耦

解耦,不仅只是对程序的扩展性而言,它可能还是你使用你的程序从一个层面向另一个层面提高的基础,请认真对待这个词语“解耦”。

我相信,它将会成为与“SOA”,“分布式”,“云计算”,“KV存储”,“高并发”一样的热门的东西,我确信这点。以后,我将会继续关注这个词语“解耦”。

今天主要是讲”代码之美“的一个话题,利用构造方法使你的对象进行一个可供注入的接口,这就是IOC里面注入的一种方式,即”构造器注入“。

 1     /// <summary>
 2     /// 统一实体
 3     /// </summary>
 4     public class EntityBase
 5     {
 6 
 7     }
 8     /// <summary>
 9     /// 统一操作
10     /// </summary>
11     public  interface IRepository
12     {
13         void Insert(EntityBase entity);
14     }
15     /// <summary>
16     /// 用户操作实现
17     /// </summary>
18     public class UserRepository : IRepository
19     {
20         #region IRepository 成员
21 
22         public void Insert(EntityBase entity)
23         {
24             throw new NotImplementedException();
25         }
26 
27         #endregion
28     }

而在构造方法去使用它的时候,一般代码是这样:

 1     public abstract class IndexFileBase
 2     {
 3         IRepository _iRepository;
 4         public IndexFileBase(IRepository iRepository)
 5         {
 6             _iRepository = iRepository;
 7         }
 8 
 9         /// <summary>
10         /// 根据实现IRepository接口的不同,Insert逻辑也是多样的
11         /// </summary>
12         /// <param name="entity"></param>
13         public void Insert(EntityBase entity)
14         {
15             this._iRepository.Insert(entity);
16         }

上面的代码,很好的实现了new对象的松耦合,这使得它具有通用的特性,一般我们在设计通用功能时,经理使用这样方式。

posted @ 2012-07-09 16:21  张占岭  阅读(2488)  评论(0编辑  收藏  举报