几个类共有的一些操作可以移到辅助类,然后通过对象组合使用:
public class OrderService { private PriceHelper priceHelper = new PriceHelper(); public double calculateOrderPrice(order) { double price = 0; for (Item item : order.getItems()) { double += priceHelper.calculatePrice(item.getProduct()); } }}public class ProductService { private PriceHelper priceHelper = new PriceHelper(); public double getProductPrice(Product product) { return priceHelper.calculatePrice(product); }}可以通过多种方式使用帮助程序类:
- 直接实例化它们(如上所述)
- 通过依赖注入
- 通过制作它们的方法
static
并以静态方式访问它们,例如IOUtils.closeQuietly(inputStream)
关闭所有InputStream
抛出异常的方法。 - 至少我的约定是只使用静态方法而不是依赖项来命名类
XUtils
,而具有依赖项的类/需要由DI容器进行管理XHelper
(上面的示例只是一个示例-不应从域驱动设计的角度对其进行讨论)



