简体   繁体   English

Java Swing:短语“赞成合成而非继承”是否适用?

[英]Java Swing: Does the phrase “favor composition over inheritance” apply?

Does the phrase "favor composition over inheritance" apply to Swing components? “赞成合成而不是继承”这个短语是否适用于Swing组件? I'd like to gather some professional opinions about the subject and which code is easier to maintain before I go ahead and design a UI. 在开始设计UI之前,我想收集一些关于这个主题的专业意见以及哪些代码更易于维护。

Does the phrase "favor composition over inheritance" apply to Swing components? “赞成合成而不是继承”这个短语是否适用于Swing组件?

Yes. 是。

The only time I extend a Swing component is when I need to override one or more of the methods. 我扩展Swing组件的唯一时间是我需要覆盖一个或多个方法。 For instance, I'll extend a JPanel when I want to override the paintComponent method. 例如,当我想覆盖paintComponent方法时,我将扩展JPanel。

All other times, my class will contain the Swing component(s) I need. 所有其他时间,我的类将包含我需要的Swing组件。 This allows me to separate my class methods: 这允许我分离我的类方法:

frame.getMethod();

from the Swing component class methods: 从Swing组件类方法:

frame.getFrame().getPreferredSize();

Try this.. 尝试这个..

1. I usually prefer using Composition over Inheritance, if i do NOT to use all the methods of a class or those methods dont apply to my class. 1.我通常更喜欢使用Composition over Inheritance, 如果我不使用类的所有方法或那些方法不适用于我的类。

2. Composition works with HAS-A relationship.. 2.作文与HAS-A关系有效。

eg: Bathroom HAS-A Tub 例如:浴室有浴缸

   Bathroom cannot be a Tub

3. Inheritance is used at its best, when its used to force some features down to its subclasses. 3. 当用于强制某些特性到其子类时 ,继承被最佳地使用。

eg: 例如:

Every Four Wheeler must have Steering, Brakes, Lights, Windows, etc... 每个四轮车必须有转向,刹车,灯,Windows等......

Must be able to Accelerate, Apply Brakes, etc.... 必须能够加速,应用刹车等....

So its subclasses must have the features that makes it a Four Wheeler. 因此它的子类必须具有使其成为四轮车的功能。

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

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