抽象类或接口.哪种方法是正确的? [英] Abstract class or interface. Which way is correct?

查看:47
本文介绍了抽象类或接口.哪种方法是正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以在抽象类或接口之间进行选择.Microsoft解决方案和Oracle解决方案:

There are two way for choosing between abstract class or interface. Microsoft solution and Oracle solution:

Microsoft,设计指南:

Microsoft, design guideline:

请使用抽象类(在Visual Basic中为MustInherit)代替接口,以使合同与实现脱钩.

http://msdn.microsoft.com/en-us/library/ms229013.aspx

Oracle,Java教程:

Oracle, The Java Tutorials:

如果抽象类仅包含抽象方法声明,则应将其声明为接口.

http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

我的问题是哪种方法是正确的?Microsoft还是Oracle解决方案?请注意,我认为在抽象类或接口之间进行选择不应取决于编程语言(Java或C#).

My question is which way is correct? Microsoft or Oracle solution? Note that I think choose between abstract class or interface should not depends on programming language (Java or C#).

推荐答案

如果我正确地回顾了我的博客,Microsoft建议使用抽象类是因为能够重用抽象类实现,这是您不能做的带有界面.

If I recall my blog reading correctly, the Microsoft advice to use abstract classes stems from the ability to reuse implementation with an abstract class, something you can't do with an interface.

还请注意,链接到的Microsoft页面是用于编写代码库以在多个项目之间共享/重用的专门指南.在这种情况下,可能是您自己编写接口的所有实现,可能是在同一程序集中.在单个产品或系统上工作的良好做法会有所不同.

Note also that the Microsoft page you linked to is specifically guidance for writing code libraries for sharing/reuse across multiple projects. The likelihood in this situation is that you'll be writing all the implementations of the interface yourself, probably within the same assembly. Good practices for working on a single product or system will vary somewhat.

我在多种语言的多种代码库中看到的一种常见方法是:

One common approach that I've seen across a number of codebases in a number of languages is this:

  • 定义一个接口以指定合同
  • 创建一个实现合同的抽象类,以提供对所有后代有用的任何通用实现
  • 为方便起见,合同的执行可以选择从基类开始,或者如果他们想要完全控制,则可以仅执行接口

.NET世界中常见的第四步是提供基于该接口的便捷扩展功能.

A fourth step common in the .NET world is to provide convenience extension functions built on the interface.

这篇关于抽象类或接口.哪种方法是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆