Home > Mobile >  How to relate two unrelated classes so they can be used in abstract class for same method
How to relate two unrelated classes so they can be used in abstract class for same method

Time:11-06

I have two json schema files from which two classes have been generated using jackson- CarSearchResponse, and HomeSearchResponse. They are not related.

In my implementation, I have created an abstract class with common functionality, and then created two concrete implementation for Car and Home.

abstract class SearchResponseFlow {
    void execute() {
        responseFlow.map(response);
    }

    abstract ResponseWrapper<SearchResponse> getData(); // SearchResponse is imaginary, what change can I make to make it accept both CarSearchResponse and HomeSearchResponse.
}

class HomeSearchResponseFlow extends SearchResponseFlow {
    void map(HomeSearchResponse resp) {
        // logic
    }

    ResponseWrapper<HomeSearchResponse> getData() {
        // logic
    }
}

class CarSearchResponseFlow extends SearchResponseFlow {
    void map(CarSearchResponse resp) {
        // logic
    }

ResponseWrapper<CarSearchResponse> getData() {
        // logic
    }
}

SearchResponse is imaginary as both CarSearchResponse and HomeSearchResponse do not implement SearchResponse since both are separately generated from different JSON schema files, what change can I make to make it accept both CarSearchResponse and HomeSearchResponse. I have to consume *SearchResponse outside also, so what can be done?

CodePudding user response:

You can do that with Generics:

class ResponseWrapper<T>{

}
class HomeSearchResponse {
}

class CarSearchResponse {
}

abstract class SearchResponseFlow<T> {

    public void execute(T response) {
        System.out.println(response);
    }

    abstract ResponseWrapper<T> getData();
}

class HomeSearchResponseFlow extends SearchResponseFlow<HomeSearchResponse> {

    @Override
    public void execute(HomeSearchResponse homeSearchResponse) {
        System.out.println(homeSearchResponse);
    }

    @Override
    ResponseWrapper<HomeSearchResponse> getData() {
        return new ResponseWrapper<>();
    }

}

class CarSearchResponseFlow extends SearchResponseFlow<CarSearchResponse> {

    @Override
    public void execute(CarSearchResponse carSearchResponse) {
        System.out.println(carSearchResponse);
    }

    @Override
    ResponseWrapper<CarSearchResponse> getData() {
        return new ResponseWrapper<>();
    }
}
  • Related