简体   繁体   English

类设计,接口或具体类

[英]Class design, Interfaces or Concrete classes

I have a problem regarding the use of interfaces vs concrete classes. 我在使用接口和具体类时遇到问题。
I have a base class that implements some common properties/methods. 我有一个实现一些常用属性/方法的基类。 Now i have two possible extensions. 现在,我有两个可能的扩展名。 Either this base class can have some property called Parameters, Or it can have another property called Children, or it can have both. 这个基类可以具有一些称为Parameters的属性,或者可以具有另一个名为Children的属性,或者可以同时具有这两个属性。

The way i see it i could create either 2 interfaces (IParameterised, IParent) or i could implement three subclasses (ParameterObject, ParentObject, ParentParameterObject). 我的看法是,我可以创建2个接口(IParameterized,IParent),也可以实现三个子类(ParameterObject,ParentObject,ParentParameterObject)。 The question is, which one of these is better design. 问题是,其中哪一项是更好的设计。 I'm leaning towards the interface method at the moment but im not an experienced programmer so any advise is welcome 我目前倾向于接口方法,但是我不是一个经验丰富的程序员,所以欢迎您提出任何建议

我认为您本人的“学习”是正确的,其他人也会同意: http : //www.artima.com/lejava/articles/designprinciples4.html

Some backgrounds on this topic that should get you going: the Liskov substitution principle (more here ) and the concept of composition over inheritance . 有关该主题的一些背景知识应该可以一臂之力Liskov替换原理 (更多信息请 参见 )以及组成而不是继承的概念。

In short, do not implement the 3 subclasses (ie, the inheritance approach): what will happen if you need 2 or 3 additional common properties/methods down the road? 简而言之,不要实现3个子类(即继承方法):如果您将来需要2或3个其他通用属性/方法,将会发生什么? With just 2 additions you are looking at 15 or so unique combinations. 仅添加2个,您就可以看到15种左右的独特组合。 For composition, look into the state and strategy patterns. 对于组成,请查看状态策略模式。

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

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