我对这些实现感到困惑。在一次采访中,面试官问我什么是组合,我给了他典型的定义,然后我为他写了这部分代码。
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.
the provision of a single interface to entities of different types.
所以你所做的(让 Bar
成为 Foo
的属性)是组合,因为 Bar
有一个 Foo< 的实例
通过将其作为属性。
面试官所做的也是组合,因为通过接口(interface) IFoo
,Bar
实现了相同的功能,并且它没有使用继承来实现这一点。这似乎是链接的 wiki 页面上记录的方式,但并不意味着您的方式是错误的。
您使用哪种方法在不同的地方实现相同的功能取决于将 Bar
作为 Foo
的属性是否有意义。
关于c# - 实现组合的正确方法(带有接口(interface)的组合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49883130/