IoC模式和factory method模式的一些区别

来源:互联网 发布:常德市优化办工作人员 编辑:程序博客网 时间:2024/06/06 19:00
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

2004年第2期的《程序员》杂志里,有一篇martin flower的关于IoC的文章。拜读过martin的《refactor》,所以关于他的文章当然要细细品味。不过在martin用来说明IoC的例子,我觉得似乎很困惑。我完全可以用一个factory method来代替IoC实现这个例子。所以不明白这两者之间有什么具体区别,还是说工厂的方法就是实现IoC的一个具体实现。

后来在jdon上看到bq的文章,正好是我需要的。

 

假设有两个类B 和 C:B作为调用者,C是被调用者,在B代码中存在对C的调用:

public class B{   private C comp;   ......}

 

当客户端调用B时,分别使用工厂模式IoC有不同的特点和区别:

  主要区别体现在B类的代码,如果使用IoC,在B类代码中将不需要嵌入任何工厂模式等的代码,因为这些工厂模式其实还是与C有些间接的联系,这样,使用IoC彻底解耦了B和C之间的联系。

  使用IoC带来的代价是:需要在客户端或其它某处进行B和C之间联系的组装。

  所以,IoC并没有消除B和C之间这样的联系,只是转移了这种联系。

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>