繁体   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