代碼之美:利用構(gòu)造方法實(shí)現(xiàn)模塊的解耦
解耦,不僅只是對(duì)程序的擴(kuò)展性而言,它可能還是你使用你的程序從一個(gè)層面向另一個(gè)層面提高的基礎(chǔ),請(qǐng)認(rèn)真對(duì)待這個(gè)詞語(yǔ)“解耦”。
我相信,它將會(huì)成為與“SOA”,“分布式”,“云計(jì)算”,“KV存儲(chǔ)”,“高并發(fā)”一樣的熱門(mén)的東西,我確信這點(diǎn)。以后,我將會(huì)繼續(xù)關(guān)注這個(gè)詞語(yǔ)“解耦”。
今天主要是講”代碼之美“的一個(gè)話題,利用構(gòu)造方法使你的對(duì)象進(jìn)行一個(gè)可供注入的接口,這就是IOC里面注入的一種方式,即”構(gòu)造器注入“。
- /// <summary>
- /// 統(tǒng)一實(shí)體
- /// </summary>
- public class EntityBase
- {
- }
- /// <summary>
- /// 統(tǒng)一操作
- /// </summary>
- public interface IRepository
- {
- void Insert(EntityBase entity);
- }
- /// <summary>
- /// 用戶(hù)操作實(shí)現(xiàn)
- /// </summary>
- public class UserRepository : IRepository
- {
- #region IRepository 成員
- public void Insert(EntityBase entity)
- {
- throw new NotImplementedException();
- }
- #endregion
- }
而在構(gòu)造方法去使用它的時(shí)候,一般代碼是這樣:
- public abstract class IndexFileBase
- {
- IRepository _iRepository;
- public IndexFileBase(IRepository iRepository)
- {
- _iRepository = iRepository;
- }
- /// <summary>
- /// 根據(jù)實(shí)現(xiàn)IRepository接口的不同,Insert邏輯也是多樣的
- /// </summary>
- /// <param name="entity"></param>
- public void Insert(EntityBase entity)
- {
- this._iRepository.Insert(entity);
- }
上面的代碼,很好的實(shí)現(xiàn)了new對(duì)象的松耦合,這使得它具有通用的特性,一般我們?cè)谠O(shè)計(jì)通用功能時(shí),經(jīng)理使用這樣方式。
原文鏈接:http://www.cnblogs.com/lori/archive/2012/07/09/2582940.html