c# - 实现组合的正确方法(带有接口(interface)的组合)

标签 c# oop interface

我对这些实现感到困惑。在一次采访中,面试官问我什么是组合,我给了他典型的定义,然后我为他写了这部分代码。

public class Foo {
    private Bar bar = new Bar(); 
}

但他声称这个实现是正确的

interface IFoo
{
    int DoSomthing();
}

class Bar : IFoo
{
    public int DoSomthing()
    {
        throw new NotImplementedException();
    }
}

哪一个是正确的?

最佳答案

编辑:我现在意识到你和你的面试官都是正确的;答案相应更新。

摘自维基百科页面Composition over inheritance :

Composition over inheritance...is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class.

Polymorphism

the provision of a single interface to entities of different types.

所以你所做的(让 Bar 成为 Foo 的属性)是组合,因为 Bar 有一个 Foo< 的实例 通过将其作为属性。

面试官所做的也是组合,因为通过接口(interface) IFooBar 实现了相同的功能,并且它没有使用继承来实现这一点。这似乎是链接的 wiki 页面上记录的方式,但并不意味着您的方式是错误的。

您使用哪种方法在不同的地方实现相同的功能取决于将 Bar 作为 Foo 的属性是否有意义。

关于c# - 实现组合的正确方法(带有接口(interface)的组合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49883130/

相关文章:

c# - Windows Developer Preview C# 版本 - 缺少功能?

c# - Java 比 C# 更适合做什么,反之亦然?

php - PDO 中的随机行数

PHP fatal error : Can't inherit abstract function

c# - 关于C#接口(interface)的问题

typescript - TypeScript 中的接口(interface)与类型

c# - WCF - IsOneway 的行为不像是 Oneway 操作

c++ - 如何在接口(interface)类中创建父类(super class)对象?

.net - 什么时候需要接口(interface)?

c# - 如何使用内置 C# 方法忽略 View 中的空值?