mercredi 25 mai 2016

How to implement a method for multiple strategies having completely different logic?

I find it hard to give this question a concret title, as I'm not really aware of how to name my type of problem. Any suggestions welcome.

I have a service to run logic that literally performs the same action (eg save a thumbnail), but contains completely different logic for different providers:

@Service
public class ThumbnailService {
    public void saveForProvider1(Prov1 url) {

    }

    public void saveForProvider2(Prov2 url) {
        //completely different logic than Provider1; also a different parameter Object "Prov2"
    }
}

Problem 1: for any new provider I have to create an additional method in that ThumbnailService.

Now at a specific point, I want to run those methods async:

@Service
public class ThumbnailServiceAsync {
    @Autowired
    private ThumbnailService delegator;

    @Async
    public class asyncSaveForProvider1(Prov1 url) { 
        delegator.saveForProvider1(url);
    }

    @Async
    public class asyncSaveForProvider2(Prov2 url) { 
        delegator.saveForProvider2(url);
    }
}

Switching by anInteger variable where I know which number stands for which provider:

int provider;
switch (provider) {
    case 1: thumbServiceAsync.asyncSaveForProvider1(url); break;
    case 2: thumbServiceAsync.asyncSaveForProvider2(url); break;
    default: throw NotSupportedException();
}

Problem 2: as you see I'm writing lots of code just for the sake of delegation to the specific provider routine. And I also have to touch at least those 3 classes mentioned when introduction any additional provider.

Question: how could I optimize this process? Especially regarding that by time more providers may be implemented. And also not only a thumbnail routine, but furhter methods that have to be implemented for every provider, but are different from their logic. Like "create a user for providerX", or "run some cleanup routine for providerX".

Aucun commentaire:

Enregistrer un commentaire