解耦,不仅只是对程序的扩展性而言,它可能还是你使用你的程序从一个层面向另一个层面提高的基础,请认真对待这个词语“解耦”。
我相信,它将会成为与“SOA”,“分布式”,“云计算”,“KV存储”,“高并发”一样的热门的东西,我确信这点。以后,我将会继续关注这个词语“解耦”。
今天主要是讲”代码之美“的一个话题,利用构造方法使你的对象进行一个可供注入的接口,这就是IOC里面注入的一种方式,即”构造器注入“。
/// <summary>
/// 统一实体
/// </summary>
public class EntityBase
{
}
/// <summary>
/// 统一操作
/// </summary>
public interface IRepository
{
void Insert(EntityBase entity);
}
/// <summary>
/// 用户操作实现
/// </summary>
public class UserRepository : IRepository
{
#region IRepository 成员
public void Insert(EntityBase entity)
{
throw new NotImplementedException();
}
#endregion
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
而在构造方法去使用它的时候,一般代码是这样:
public abstract class IndexFileBase
{
IRepository _iRepository;
public IndexFileBase(IRepository iRepository)
{
_iRepository = iRepository;
}
/// <summary>
/// 根据实现IRepository接口的不同,Insert逻辑也是多样的
/// </summary>
/// <param name="entity"></param>
public void Insert(EntityBase entity)
{
this._iRepository.Insert(entity);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
上面的代码,很好的实现了new对象的松耦合,这使得它具有通用的特性,一般我们在设计通用功能时,经理使用这样方式。
原文链接:http://www.cnblogs.com/lori/archive/2012/07/09/2582940.html