Java抽象类或静态实用程序类设计选择 [英] Java Abstract Class or Static Utility Class Design Choice
问题描述
我正在实施一些策略(策略模式),这些策略有一些共同的行为,假设我有1个上下文和3个策略,策略中使用的一些操作是共享的,有些只需要2个其他只是其中的1个策略。
选项1:制作一个AbstractStrategy类
- 我正在使用Java,这样立即
将在
的未来中使用此功能。 - 继承会导致。
在山脊结构中。 - 操作将是最终的。
选项2:创建一个Util类的静态帮助器
- 灵活,但由于某种原因感觉到代码气味
- 不成立。
任何建议或偏好?
注意我正在工作的级别是策略级别,而不是上下文级别(见维基百科链接)。
有一个原因...一个巨大的原因...在抽象类或接口上使用静态Util类。
所以你可以在以后添加更多的方法。
使用抽象类或接口,您对该类/接口的任何更改都必须在所有类中更改从它继承。如果您正在编写一个公共API,这是特别有问题的。
Java框架具有遍历整个静态方法的util类。最着名的是在 java.util
包: 集合
和 数组
。
I am implementing a few strategies (Strategy Pattern) which have some common behavior and am undecided where the common operations should live.
- Assuming I 1 context and 3 strategies, some of the operations used in the strategies are shared, some are needed only by 2 others just be 1 of the strategies.
- There is no member level state shared, therefore the only operations are effectively stateless.
- The intention of the operations are to support the formatting of state to a file, like a view helper.
Option 1: Make an AbstractStrategy class
- I'm using Java so this immediately takes away using this feature in the future.
- Inheritance tends to result. in a ridge structure.
- Operations would be final.
Option 2: Create a Util class of static helpers
- Flexible, but feels like a code smell for some reason.
- Not ridged.
Any recommendations or preferences?
Note the level I am working at is the Strategy level, not the Context level (see wikipedia link).
There is one reason... one huge reason... to use a static Util class over an abstract class or interface.
So you can add more methods at a later date.
With an abstract class or interface, any change you make to that class/interface has to be changed in all classes that inherit from it. This is especially problematic if you're writing a public API.
The Java framework has util classes with static methods scattered throughout. The most well known ones are in the java.util
package: Collections
and Arrays
.
这篇关于Java抽象类或静态实用程序类设计选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!