构建超类 [英] Structuring SuperClasses

查看:83
本文介绍了构建超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有3个这样的班级:

   |Abstract Class: Building|
   |int windows;            |
   |int rooms;              |
          |
          |
   |Abstract Class: House extends Building|
   |int familyMembers;                    |
          |
   |Class: MobileHome extends House|
   |int wheels;                    |

现在,我正在尝试找出构建程序的最佳方法,因为显然窗户和房间的数量将取决于House的子类,但是所有建筑物都有窗户(至少出于该程序的考虑)他们是这样).因此,这就是为什么它们属于建筑类,但这些窗户的数量取决于最低的子类的原因,因为如果我创建另一个名为mansion的类,该类扩展了House,显然一个豪宅的窗户将比移动房屋多. >

最后,我计划将我的建筑类和其他抽象类做得非常详细,最后有大约一百种不同的属性(我列出的字段只是示例),所以我想知道是否有人对构造MobileHome对象的一种干净方法,可能只是在构造函数调用中传递一个对象,而不是使构造函数使用数百个参数.

我在网上找到的所有示例都相对简单,通常只扩展一个类并仅使用几个字段,因此使构造函数相对容易,所以我只是在寻找一种优雅的大规模解决方案.

SideNote:如果有人对构建此类的更好方法有任何想法,也许可以通过将它们分解开来,我将不胜感激.

解决方案

您可能想查看 go 一书中的创新设计模式.特别是构建器听起来很合适.这应该给您和如何构造您的类的想法.您可以在Java 此处中找到一些示例.

Say i have 3 classes like this:

   |Abstract Class: Building|
   |int windows;            |
   |int rooms;              |
          |
          |
   |Abstract Class: House extends Building|
   |int familyMembers;                    |
          |
   |Class: MobileHome extends House|
   |int wheels;                    |

Now i am trying to figure out the best way to structure my program, because obviously the number of windows and rooms will depend on the subclass of House, however all buildings have windows (at least for the sake of this program they do). So that is why they are in the building class but the number of those windows will depend on the lowest subclass because if i make another class called mansion which extends House obviously a mansion will have more windows than a mobile home.

In the end I plan on making my building class, and other abstract classes very detailed with about a hundred different attributes at the end (the fields i have listed are just examples) so i was wondering if anyone had any idea for a clean way to construct a MobileHome object maybe passing just one object down the constructor calls rather than making constructors that take hundreds of parameters.

All the examples i found online were relatively simple usually only extending one class and using only a couple of fields so making the constructors was relatively easy so I'm just looking for an elegant large scale solution.

SideNote: If anyone has any ideas on a better way to structure these classes, maybe by breaking them up more i would appreciate any opinions.

解决方案

You might want to check out the creational design patterns in the gof book. In particular builder sounds like it might be a good fit. This should give you and idea of how to structure you classes. You can find some examples in java here.

这篇关于构建超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆