vendredi 28 mai 2021

What's an appropriate design for creating different objects/invoking different methods depending on use case?

I'm not too sure what this use-case is called but let me explain: I am developing a service that uploads data. My service handles different types of uploads and each upload type is unique e.g. content of UPLOAD_A != content of UPLOAD_B.

The data comes to me a json file. From the json file, I know what type of upload it is. I need to parse this json into an appropriate UploadDataX object. For example, if I get a json data file for UPLOAD_A, I need to serialise this into an UploadDataA object.

Once I have my UploadDataX object, I will need to upload the data. I do this by using an external client object: UploadClient(). However, I need to invoke specific upload methods depending on the data type. For example, for an UPLOAD_A type, I need to invoke UploadClient().uploadDataA(UploadDataA) and for an UPLOAD_B type, I need to invoke UploadClient().uploadDataB(uploadDataB).

The problem is that I do not own any of these UploadDataX and the client object. Unfortunately, the UploadDataX do not come under a super-class. I'm wondering what is an effective design pattern for dealing with this use-case?

I can think of a brute force solution, using simple switch-case statements:

// BRUTE FORCE SOLUTION
public void upload(UploadType uploadType, String jsonString) {
   switch (uploadType) {
      case UPLOAD_A: {
         UploadDataA uploadDataA = Gson().fromJson(jsonString, UploadDataA.class);
         UploadClient().uploadDataA(uploadDataA);
         break;
      }
      case UPLOAD_B: {
         UploadDataB uploadDataB = Gson().fromJson(jsonString, UploadDataB.class);
         UploadClient().uploadDataB(uploadDataB);
         break;
      }
   }
   ...
}

as you can see, this seems repetitive and I can't help but feel there is a better design approach. I was thinking about a Factory pattern but I want to see what everyone else thinks.

Aucun commentaire:

Enregistrer un commentaire