开发者

Class design 'dilemma'

I never did proper class design, so bear with me.

Let's say we have a Project class. Then let's say we have a ProjectGroup class that has the 开发者_如何学编程same members as the Project class, plus a list of Projects.

Should ProjectGroup be the superclass of Project or is ProjectGroup a specialization of Project and the former should be a subclass of the latter?


I won't bother you with theory, because you're probably in a hurry to get a quick answer. So here it goes:

If your two classes are actually implying they should be related by inheritance then ProjectGroup should inherit from Project class. This is how it would look like in C#:

public class ProjectGroup: Project ...

If they are not, but they use some common class members (that define their state and some functionality over that state), then I'd write an interface and implement it in both classes. C# code again:

public interface ICommonState ...

public class Project: ICommonState ...

public class ProjectGroup: ICommonState
{
    IEnumerable<ICommonState> projects
    ...
}

Edit

If your classes are actually Project and ProjectGroup and they both have properties like ID and Name in common (for instance), they still shouldn't be inherited. They just happen to have properties with the same name, but they are basically different entities.

They could both either

  • implement an ICommonEntity interface - use it when they have the same state+functionality but functionality behaves differently in each of them
  • inherit from CommonEntity class - use it when functionality is completely identical; this way you'll follow the DRY (don't repeat yourself) philosophy

So your component may be an interface or a class (when using composite pattern).

Direct inheritance between two classes is more suitable where entities imply on being in relation to each other. Like User and Person classes. They can be inherited either way. Depending on the business scenario.

class User: Person  

This would be the case where you have an application with contacts. Some of them are also users of this very same application.

class Person: User  

This would be a web site where you can register as a user. In case you fill up some personal details as well your user data becomes of type Person.


It sounds like you might want the Composite pattern. Both LeafProject and CompositeProject implement the Project interface, and CompositeProject also holds a collection of Project instances.


if the member list of projects is unique to projectgroup and does not apply to all types of projects, then make project your super/base class and derive projectgroup from project.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜