jeudi 7 octobre 2021

What pattern should I use to create an object?

I have a simple interface

     interface Content {
         OffsetDateTime getCreationDateTime(); 
         // another methods
     }

And many classes that implement this interface

    class Video implements Content {}
    class ShortClip implements Content {}
    class UpcomingBroadcast implements Content {}
    class LiveBroadcast implements Content {}
    class EndedBroadcast implements Content {}
    // another...

I get data from external API and create a concrete class using it. For example:

    ApiData data = (new ApiClient()).getData(int someParameter);
    String value1 = data.getValue1();
    if(value1.equals("A")) {
        String value2 = data.getValue2();
        if(value2.equals("B")) {
            return new UpcomingBroadcast(/* some values from api in constructor */);
        } else {
            return new LiveBroadcast(/* ... */);
        }
    } else {
        String value3 = data.getValue3();
        if(value3.equals("C")) {
            return new ShortClip(/* ... */);
        } else {
            // Please remember this place in the code.
        }
    }

At this point, according to the data from the API, I cannot unambiguously determine which class object will be created. For example it can be Video or EndedBroadcast. To determine exactly, I have to use my database:

    String value4 = databaseRepository.getValue();
    if(value4.equals("D")) {
        return new Video(/* ... */);
    } else {
        return new EndedBroadcast(/* ... */);
    }

I need to access the database only in the highlighted section of the code. To avoid nested if-else statements, I wanted to use a design pattern (for example, Factory), but I can't do it because different classes have their own algorithm for determining its type. How can I replace nested if-else statements with cleaner code?

Aucun commentaire:

Enregistrer un commentaire