繁体   English   中英

将 collections 从一种类型转换为另一种类型的策略

[英]Strategies for converting collections from one type to another

将带有 EO(实体对象)的 ArrayLists 转换为 DTO 对象的 ArrayLists 或 Ids 的 ArrayLists 的最有效方法是什么。 请记住,每个 EO 可能包含也是 EO 的属性,或 EO 的 collections,应在内部转换为 DTO,或省略(取决于转换策略)。 一般来说,有很多样板代码。

希望它像这样简单:

collectionOfUsers.toArrayList<UserDTO>(); 

或者..

collectionOfUsers.toArrayList<IEntity>();
// has only an id, therefore it will be converted
// into a collection of objects, having only an id.

当然,这也可以很好:

collectionOfUsers.toArrayList<Long>()
// does the same thing, returns only a bunch of ids

当然,也应该有人持有映射策略,例如工厂或某事。

有什么建议么?

您可以只使用一个简单的界面来模拟转换。

interface DTOConvertor<X,Y> {
    X toDTO(Y y);
}

public static List<X> convertToDTO(Collection<Y> ys, DTOConvertor<X,Y> c) {
    List<X> r = new ArrayList<X>(x.size());
    for (Y y : ys) {
        r.add(c.toDTO(y));
    }
    return y;
}

请注意,这与实现map功能的库相同。

在效率方面,我猜你会遇到问题,因为实体对象将(可能)从数据库中获取。 你可以让人际关系急于探索这是否有什么不同。

您应该创建一个通用方法来从一种类型转换为另一种类型。 这是一个简单的界面:

public interface XFormer<T,U> {
    public T xform(U item);
}

然后,您将在通用转换方法中使用它:

public static <T, U> List<T> xForm(List<U> original, XFormer<T, U> strategy) {
    List<U> ret = new ArrayList<U>(original.size());
    for (U item: original) {
        ret.add(strategy.xform(item));
    }
    return ret;
}

一种用法可能如下所示:

List<String> original;
List<Long> xFormed = xForm(original, new XFormer<Long, String>() {
                         public Long xForm(String s) {
                           return Long.parseLong(s);
                         }
                     });

我在我的一个开源项目中使用了同样的策略。 以第 166 行的JodeList为例。 在我的情况下它有点简化,因为它只能从 Jode 转换为任何类型,但它应该能够扩展到任何类型之间的转换。

考虑使用 Apache Commons BeanUitls.populate()。

它会将每个等效属性从一个 Bean 填充到另一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM