簡體   English   中英

Java-使用繼承處理泛型

[英]Java - Handling generics with inheritance

我有一個代表供應商服務的類,它們的所有服務都具有身份驗證和execute方法。

我開始考慮一個抽象類,如下所示。 問題是他們的每個服務都需要一個不同的請求對象,因此我想到了使用泛型。 問題是,如果使用它,我將無法處理每個請求對象的細節。 每個孩子都必須使用該類型的某些方法。

1)我應該嘗試以這種方式嘗試,還是從抽象類中刪除此executeRequest方法,並且每個子類都以正確的類型實現它?

2)我總是聽到“優先考慮組成而不是繼承”。 我應該將executeRequest移到接口嗎?

提前致謝!

public abstract class VendorService  {

    private final VendorInitialization VendorInitialization;

    //a bean with some auth params
    public VendorService(VendorInitialization VendorInitialization) {
        this.VendorInitialization = VendorInitialization;
    }

    protected abstract <T> boolean validateRequest(T requestObject) throws VendorServiceBadRequest;

    protected abstract <T, P> P executeRequest(T requestObject);
}


public class VendorServiceAllocation extends VendorService {

    public VendorServiceAllocation(VendorInitialization VendorInitialization) {
        super(VendorInitialization);
    }

    @Override
    protected <T> boolean validateRequest(T requestObject) throws VendorServiceBadRequest {

        //List<BeanAllocation> requestObject = new Arraylist<>(); //I was using like this before

        //TODO: how to handle it as list of on this specific case?
        if (requestObject == null || requestObject.size() == 0) {
            throw new VendorServiceBadRequest(String.format("The list must have at least one element"));
        }

        //TODO: requestObject.get(0).getMySpecificFieldFromBeanAllocation will not work

        //some checks
        return true;
    }

    @Override
    protected <T, P> P executeRequest(T requestObject) {
        //executes and return a list of objects specific to this class
        return new List<BeanAllocationResponse>();
    }
}

編輯,以進行澄清:在子類VendorServiceAllocation ,我需要使用一些特定於該類型的方法。

例如:在executeRequest ,我需要調用requestObject.customFunctionFromChild()

我認為尼斯曼打在了頭上,盡管我不太確定你在問什么。 例如。

abstract class Service<T,P>{
    abstract public P processRequest(T t);
}

然后,您可以用以下兩種方法之一來實現它。

class StringService extends Service<String, String>{
    public String processRequest(String t){
         return t;
    }
}

或者,您可以將其保留為通用類型,而實際實例將具有不同的類型。

class OtherService<T> extends Service<T, String>{
    public String processRequest(T t){
        return t.toString();
    }
}

您可以將其用作

OtherService<Integer> is = new OtherService<>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM