本文介绍了组合总是比继承更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几篇文章,它们主张继承优先于继承,并且我坚信在所有这些情况下,重组可能都是更好的主意.但是继承是否仍然具有比组合有明显优势的方案?我是否还必须再次在组成的类中实现所有属性和方法(如下例所示)?我确定我在这里遗漏了一些东西...

I have read several articles favoring composition over inheritance and I am convinced that in all those cases composition may be better idea. But does inheritance still has scenarios where it has a clear advantage over composition? Also do I have to implement all properties and methods again in a composed class (as shown in example below)? I am sure I am missing something here...

//May have numerous methods and properties
class BaseEngine
{
	...
	Property101 { get; set; }
	...
	Method101 (parameters...)
	...
}

//Inheritance
Class SpecialEngine
{
	Override Property101 { get; set; }
	Override Method101 (parameters...)
}

//Composition
Class SpecialEngine
{
	BaseEngine baseEngine = new BaseEngine();

	//Do I need to implement all methods and properties again so that they are callable from special engine?
	Property0 { return baseEngine.Property0 }
	Property1 { return baseEngine.Property1 }
	...
	Property100 { return baseEngine.Property0 }
	Property101 { return special_logic; }

	Method0 { return baseEngine.Method0 }
	Method1 { return baseEngine.Method1 }
	...
	Method100 { return baseEngine.Method100 }
	Method101 { return special_logic; }
}

推荐答案


这篇关于组合总是比继承更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 16:32
查看更多