本文介绍了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, likeIOUtils.closeQuietly(inputStream)
closes anInputStream
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 containerXHelper
(上面的示例只是一个示例 - 不应该根据域驱动设计进行讨论)
(The example above is just a sample - it shouldn't be discussed in terms of Domain Driven Design)
这篇关于java中的帮助对象是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!