简体   繁体   English

通用类型的使用方法

[英]Use Method of generic type

I am currently writing an XML converter for a supply chain project. 我目前正在为供应链项目编写XML转换器。 We use Requests and Orders. 我们使用请求和订单。

The converter has multiple method that currently do same but are separately implements for requests and orders. 转换器具有多种当前执行相同方法的方法,但它们是请求和订单的单独实现。

I have therefore created an abstract class to improve maintainability of the code and used a generic type: 因此,我创建了一个抽象类来提高代码的可维护性,并使用了通用类型:

public abstract class AbstractConverter<T extends BusinessObject>

Then I have the specific implementations for the actual converters 然后我有实际转换器的具体实现

public class OrderConverter extends AbstractConverter<Order>
public class RequestConverter extends AbstractConverter<Request>

As I said, I have several methods in the two specific classes that basically do the same, so I naturally want them in the abstract class. 就像我说的那样,我在两个特定的类中有几种方法基本上可以做到这一点,所以我自然希望它们在抽象类中。 I have now added the following method to the abstract class: 现在,我在抽象类中添加了以下方法:

protected Comment createComment(T obj) {
    String remark;
    if (obj instanceof Order) {
        remark = ((Order) obj).getRemark();
    } else if (obj instanceof Request) {
        remark = ((Request) obj).getRequestRemark();
    } else {
        throw new IllegalArgumentException("This method does not support objects of the type " + obj.getClass().toString());
    }
    return new Comment(remark);
}

My question now is: is this the way to go or is there a more elegant way to use generics in this context? 我现在的问题是:这是走的路还是在这种情况下使用泛型的一种更优雅的方式?

I need this solved but I also want to use good style. 我需要解决这个问题,但我也想使用好的样式。

The natural object oriented solution is to make createComment an abstract method 面向对象的自然解决方案是使createComment为抽象方法

protected abstract Comment createComment(T obj);

and let the subclasses implement it: 并让子类实现它:

public class OrderConverter extends AbstractConverter<Order> {
     protected Comment createComment(Order order) {
           return new Comment(order.getRemark());
     }
}

public class RequestConverter extends AbstractConverter<Request> {
     protected Comment createComment(Request request) {
           return new Comment(request.getRequestRemark());
     }
}

I'd suggest extracting the getRemark method to an interface which both Request and Order implements. 我建议将getRemark方法提取到RequestOrder实现的接口。

That way you can simply check if the incoming generic object is an instance of the interface. 这样,您可以简单地检查传入的通用对象是否是接口的实例。

protected Comment createComment(T obj) {
    if (obj instanceof Remarkable) {
        return new Comment(((Remarkable) obj).getRemark());
    }
    throw new IllegalArgumentException("This method does not support objects of the type " + obj.getClass().toString());
}

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

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