java中的帮助对象是什么?

编程入门 行业动态 更新时间:2024-10-28 20:27:21
本文介绍了java中的帮助对象是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我遇到过几次被称为辅助对象的事情......任何人都可以详细说明这些辅助对象是什么以及我们为什么需要它们?

I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?

推荐答案

一些类共有的一些操作可以移动到辅助类,然后通过对象组合使用它们:

Some operations which are common to a couple of classes can be moved to helper classes, which are then used via object composition:

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); } }

使用辅助类可以通过多种方式完成:

Using helper classes can be done in multiple ways:

  • 直接实例化(如上所述)
  • 通过依赖注入
  • 使他们的方法 static 并以静态方式访问它们,例如 IOUtils.closeQuietly(inputStream)关闭一个 InputStream 没有抛出异常。
  • 至少我的约定是只用静态方法命名类而不依赖 XUtils ,而且反过来依赖/需要由DI容器管理的分类 XHelper
  • Instantiating them directly (as above)
  • via dependency injection
  • by making their methods static and accessing them in a static way, like IOUtils.closeQuietly(inputStream) closes an InputStream wihtout throwing exceptions.
  • at least my convention is to name classes with only static methods and not dependencies XUtils, and classees that in turn have dependencies / need to be managed by a DI container XHelper

(上面的示例只是一个示例 - 不应该根据域驱动设计进行讨论)

(The example above is just a sample - it shouldn't be discussed in terms of Domain Driven Design)

更多推荐

java中的帮助对象是什么?

本文发布于:2023-06-07 15:35:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!