Java实用程序类与服务 [英] Java Utility Class vs. Service
问题描述
实用程序类(具有静态方法的类)和Service类(具有提供服务的公共方法的类)之间的Java有什么区别。例如,可以认为,加密对象(提供加密,解密,散列或获取盐值的方法)是一个服务提供者,但是许多使用静态方法将此功能组合到一个Utility类中,如CryptoUtil.encrypt(..) )。我试图找出哪种方式遵循更好的设计。想法?
What's the difference in Java between a utility class (a class with static methods) and a Service class (a class with public methods that provides a "service"). For example, one can argue that a cryptographic object (providing methods to encrypt, decrypt, hash or get a salt value) is a Service provider, but many group this functionality into a Utility class with static methods, like CryptoUtil.encrypt(...). I'm trying to figure out which way follows better "design". Thoughts?
推荐答案
可以通过使用不同的服务对象来获得不同的行为。实用程序类中的静态方法不能被换出。这对于测试,更改实现和其他目的非常有用。
Different behaviors can be obtained by using different service objects. Static methods in a utility class can't be swapped out. This is extremely useful for testing, changing implementations, and other purposes.
例如,你提到一个 CryptoUtil
加一个 encrypt
方法。有不同的对象可以支持不同的加密策略,不同的消息收件人等,这将非常有用。
For example, you mention a CryptoUtil
with an encrypt
method. It would extremely useful to have different objects that could support different encryption strategies, different message recipients, etc.
这篇关于Java实用程序类与服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!