简体   繁体   English

Java泛型 - 使用泛型接口及其实现的最佳方式

[英]Java Generics - Best way to use generic interface and its implementation

I have an interface MessageHandler which takes a generic type T and an implementation MessageHandlerImpl which operates on concrete type CustomObject.我有一个接口 MessageHandler,它采用泛型类型 T 和一个在具体类型 CustomObject 上操作的实现 MessageHandlerImpl。 And then I am using this in another client class as per shown below:然后我在另一个客户端类中使用它,如下所示:

public interface MessageHandler<T> { 

    void validate(T t);
    
    void process(T t);
    
    default void handle(T t) {
        validate(t);
        process(t);
    }
}

public class MessageHandlerImpl implements MessageHandler<CustomObject> {

    @Override
    public void validate(CustomObject message) {}
        
    @Override
    public void process(CustomObject message) {}
}

public class AnotherClientClass {
    
    //option - 1
    MessageHandlerImpl handler = new MessageHandlerImpl();
    //option - 2
    MessageHandler<CustomObject> handler = new MessageHandlerImpl();

    public void getMessage() {
        String messageStr = getMessageFromAnotherMethd();
        CustomObject messageObj = convertToCustomObject(messageStr);
        
        handler.handle(messageObj);
    }
}

I have couple of questions here :我在这里有几个问题:

  1. Is option-1 good as per best development practices, I think no as we are using concrete type for reference variable ?根据最佳开发实践,选项 1 是否良好,我认为不是,因为我们使用具体类型作为参考变量?
  2. Option-2 looks suitable but here I have to declare type (CustomObject) again which I feel like extra baggage as MessageHandlerImpl has already done that, am I missing something ? Option-2 看起来很合适,但在这里我必须再次声明类型 (CustomObject),我觉得这是额外的负担,因为 MessageHandlerImpl 已经这样做了,我错过了什么吗?

Generics are irrelevant here.泛型在这里无关紧要。 Use the same guidelines you'd use to select the appropriate declared variable type in general.通常使用与选择适当的声明变量类型相同的准则。

More broadly, you have a poor design by calling new at all .更广泛地说,通过调用new ,你的设计很糟糕。 Instead, make the handler a constructor parameter.相反,使handler成为构造函数参数。 In this case, definitely use the supertype MessageHandler<CustomObject> (or, even better, MessageHandler<? super CustomObject> or even Consumer<? super CustomObject> ).在这种情况下,一定要使用超类型MessageHandler<CustomObject> (或者,甚至更好, MessageHandler<? super CustomObject>甚至Consumer<? super CustomObject> )。

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

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