使用像IStartable這樣的概念有什么好處?

[英]What are the advantages of using a concept like IStartable?


Instead of using an interface like this:

而不是使用這樣的界面:

public interface IStartable
{
    void Start();
    void Stop();
}

I usually just make the constructor of an object run the Start() code, and implement IDisposable so that the dispose method runs the Stop() code.

我通常只是使對象的構造函數運行Start()代碼,並實現IDisposable,以便dispose方法運行Stop()代碼。

Is it just a matter of style? Or am I missing something important by not having something like IStartable? All I see is extra complexity, because you have to maintain it's started/stopped state.

這只是風格問題嗎?或者我沒有像IStartable這樣的東西錯過了一些重要的東西?我所看到的只是額外的復雜性,因為你必須維持它的啟動/停止狀態。

What are the pros and cons of using start/stop vs using ctor/dispose, especially in the context of an IoC/DI container?

使用啟動/停止與使用ctor / dispose的優缺點是什么,特別是在IoC / DI容器的上下文中?

EDIT: Great answers, you've convinced me to use an interface for startable objects. I can't decide who's answer is the best so I'll accept whoever has the most up votes after 24 hours.

編輯:很棒的答案,你說服我使用一個可啟動對象的界面。我無法確定誰的答案是最好的,所以我會接受24小時后得票最多的人。

3 个解决方案

#1


The general advantage to using an interface is that they're self-describing and self-advertising. If there's no interface, you don't have a way to ask an object, "can you be started and stopped?" If you do use an interface, by contrast, you can query objects to see which of them will respond to those kinds of messages. Then you can be safely guaranteed that such objects have implemented the functionality encapsulated by the interface.

使用界面的一般優點是它們是自我描述和自我廣告。如果沒有接口,你就無法詢問一個物體,“你可以開始和停止嗎?”相反,如果使用界面,則可以查詢對象以查看哪些對象將響應這些類型的消息。然后,您可以安全地保證這些對象已實現接口封裝的功能。

#2


in general, constructors should produce a properly-initialized object

通常,構造函數應該生成一個適當初始化的對象

and nothing more!

僅此而已!

#3


It could possibly depend on what, specifically, you mean to be happening when you say Start(). But in general, mixing object initialization with routine execution (especially stateful and/or long-running execution!) violates SoC.

當你說Start()時,它可能取決於你的意思。但一般來說,將對象初始化與例程執行混合(特別是有狀態和/或長時間執行!)會違反SoC。

It also leaves a great deal of ambiguity. To a consumer, for a given object how do we know it is "starting" when we invoke the ctor? "For this given object, which implements no contract, I must leave it to hope in the author that it conforms to my expectations"? An interface makes the presence and availability of the action explicit.

它也留下了很多含糊之處。對於消費者,對於給定的對象,當我們調用ctor時,我們如何知道它是“開始”的? “對於這個沒有簽訂合同的特定對象,我必須讓作者希望它符合我的期望”?界面使操作的存在和可用性顯式化。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/05/26/725b37d73658490f70161521bc1928e.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com