Structuring SuperClasses

99封情书 提交于 2019-12-12 03:53:35

问题


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.


回答1:


The idea with you super-class is to create the most general class as possible with fields and methods that are common to all sub-classes. So put as many of the 'hundreds' of parameters as you can in the parent classes.

If you have that many parameters it might be worth working out if you can group those into classes as well and then making objects of those classes as members of yours. For example in the mobile home instead of having fields describing every single detail you want to group the details together. Basically if you have hundreds of fields in one class something is up with your design, there must common subgroups to all those fields.




回答2:


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.



来源:https://stackoverflow.com/questions/44711002/structuring-superclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!