简体   繁体   English

基于接口的编程,我做得对吗?

[英]Interface based programming, Am I doing it right?

OK so I decided to start using interfaces in my code base and this works out pretty well for certain tasks. 好的,所以我决定开始在我的代码库中使用接口,这对于某些任务来说非常好。 For instance I have a URL builder class that implements IUrlBuilder and now the implementation does not matter. 例如,我有一个实现IUrlBuilder的URL构建器类,现在实现并不重要。 Brilliant but take this interface for example. 很棒,但以此界面为例。

namespace SproutMessagingFramework.Webtext.Interfaces
{
using System.Net;

public interface ICookieJar
{
    CookieCollection Collection { get; set; }
    CookieContainer Container { get; set; }

    void AddResponse(HttpWebResponse Response);
    void AddResponse(HttpWebResponse Response, string Path, string Domain);
}
}

This interface in my view is pretty concrete, those two methods wont be doing much else than what the concrete class will already be doing. 在我看来,这个界面非常具体,这两个方法除了具体类已经做的事情之外不会做太多其他事情。 So why did I make it an interface? 那我为什么要把它变成一个界面呢? Well my thinking is what if I need to change the Implementation of AddResponse? 好吧,如果我需要更改AddResponse的实现,我的想法是什么?

Is this correct or am I just bloating the codebase? 这是正确的还是我只是膨胀代码库?

Interfaces can be designed with a 1:1 correspondence to a particular class. 接口可以设计为与特定类别1:1的对应关系。 This allows (among other things) integration with mock frameworks, where you substitute a pretend cookie jar for the real one while validating the behaviour of a cookie monster in a test environment. 这允许(除其他外)与模拟框架的集成,其中您在假设测试环境中的cookie怪物的行为的同时用假装的cookie罐替换真实的cookie。

It is more common, however, for interfaces to define a subset of the class's capabilities, and can often be orthogonal in purpose to the class itself. 然而,更常见的是,接口定义类的能力的子集,并且通常可以与类本身正交。 A good example of an orthogonal interface is IDisposable. 正交接口的一个很好的例子是IDisposable。 A class implements IDisposable when it wants to support clean reclamation of unmanaged resources such as sockets, file descriptors, etc., though resource cleanup is not what the class is really designed for. 当一个类想要支持非托管资源(如套接字,文件描述符等)的干净回收时,它实现了IDisposable,尽管资源清理不是该类实际设计的内容。

Another common use is to provide a unified container model, such as ICollection and IEnumerable. 另一个常见用途是提供统一的容器模型,例如ICollection和IEnumerable。

Finally, classes often implement several interfaces, usually corresponding to orthogonal cross-sections of their capabilities. 最后,类通常实现几个接口,通常对应于其功能的正交横截面。

Even if there's only one way to implement the AddResponse methods themselves, I can still imagine implementations of ICookieJar that do something before forwarding the call to some concrete instance of the interface. 即使只有一种方法来实现AddResponse方法本身,我仍然可以想象ICookieJar实现在将调用转发到接口的某个具体实例之前ICookieJar

For example, an implementation that adds diagnostic logging, or one that transparently renames cookies as they're stored. 例如,添加诊断日志记录的实现,或者在存储时透明地重命名cookie的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM