Interfaces Topic(zz)

Interfaces Wow, 在开发时、架构时、思考时,Interfaces都是我们这族人常常使用的,

在开发工作中,我常常用Interfaces作为参数类型用于方法的signatures.

此贴就是解释为什么choose to do this,& the benefits of coding...

让我们来看两个操作数据的方法

第一个方法:创建数据库的连接,发出请指令,查询想要的数据结果返回一个结果。

第二个方法:通过while(reader.Read())填充一个IList<Entity>.

代码如下:

public IList<Article> Get() {  
    SqlConnection connection 
= new SqlConnection(_connectionString);  
    SqlCommand command 
= new SqlCommand();   
    command.Connection 
= connection;  
    command.CommandType 
= CommandType.StoredProcedure; 
    command.CommandText 
= "GetAllArticles";    
    SqlDataReader reader 
= command.ExecuteReader(CommandBehavior.SingleResult); 
    
return FillArticles(reader);
}

private IList<Article> FillArticles(SqlDataReader reader) {
    List
<Article> articles = new List<Article>();
    
while (reader.Read()) {
        Article article 
= new Article();
        article.ArticleID 
= (int)reader["ArticleID"];
        article.Title 
= reader["Title"];
        article.Body 
= reader["Body"];
        article.Published 
= (DateTime)reader["Published"];
        articles.Add(article);
    }
    
return articles;

FillArticles方法是期待一个具体类与其连接(及:SqlDataReader).
现在让我们来假设,如果你的数据不在存储于数据库,而把数据源改为其他方式Store,比如XML Files.
 
这时一般都是重新写一个构建一个Get方法,然后以 to handle Xml access的方式,重新pass一个XmlDataReader to the FillArticles()方式。
但不幸的是,你将得到一个Error Information, 因为你的FillArticles()是期待一个SqlDataReader与其互访的。

那我们如果解决此问题呢?
Well,very easy,因为SqlDataReader & XmlDataReader都是 implement an Interface,
此Interface名为IDataReader.接下来只要Changing the paremeter type from SqlDataReader to IDataReader即可,这样你就可以不需要更改,或者重新此方法。
是不是很不错的选择呢。
代码如下:

private IList<Article> FillArticles(IDataReader reader) {
    List
<Article> articles = new List<Article>();
    
while (reader.Read())
    {
        Article article 
= new Article();
        article.ArticleID 
= (int)reader["ArticleID"];
        article.Title 
= reader["Title"];
        article.Body 
= reader["Body"];
        article.Published 
= (DateTime)reader["Published"];
        articles.Add(article);
    }
    
return articles;
}


其实当然看清事物的本质是什么,有时可以帮助自己很好的认识它,同时更可以很好使用它,

即方便开发etc.

另外在VS当中好像有一个key short(Alt+ Ctrl +J)可以查找,查看具体类的Base Type.

当然如果你安装了ReSharper, 它也是可以及时告知你。


以上就是Inerfaces & Concrete 之的话题。

有关于Interface与It的话题还是比较多的,下面我给几个资源

  • Abstract base class over interface
       
  • API Design Myth: Interface as Contract
       
  • interface-vs-abstract-class
       
  • Using objects or repository interface in constructor


  •  

    posted @ 2008-11-06 23:29  stu_acer  阅读(146)  评论(0编辑  收藏  举报