Java 实用程序类与服务 [英] Java Utility Class vs. Service

查看:29
本文介绍了Java 实用程序类与服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中实用程序类(具有静态方法的类)和服务类(具有提供服务"的公共方法的类)之间有什么区别.例如,有人可能会争辩说,一个加密对象(提供加密、解密、散列或获取盐值的方法)是一个服务提供者,但许多人将此功能分组为具有静态方法的实用程序类,如 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.

例如,您提到带有 encrypt 方法的 CryptoUtil.拥有可以支持不同加密策略、不同消息接收者等的不同对象会非常有用.

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屋!

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