lundi 28 mars 2016

Efficient design pattern to perform a one-to-one mappings from a type hierarchy to set of values

I would like to call an external vendor's api method on types in my local library. The vendor's method takes a setting in the form of a string which can take on several values, say "Cat" and "Dog". I am performing the mapping from my type to the vendor's setting string thus:

public class Program {
    interface LocalType {}
    static class LocalCat implements LocalType {}
    static class LocalDog implements LocalType {}

    // Calls some API to get the animal's sound
    interface AnimalSounds {
        void playSound(LocalType t);
    }

    // Vendor-specific implementation
    static class VendorSounds implements AnimalSounds{
        private static VendorAPI api = new VendorAPI();
        @Override public void playSound(LocalType t) {
            // Map local type to vendor setting
            if (t instanceof LocalCat)
                api.vendorMethod("Cat");
            else if (t instanceof LocalDog)
                api.vendorMethod("Dog");

        }
    }

    // API defined externally by vendor (reproduced here for illustration)
    static class VendorAPI {
        static void vendorMethod(String type) {
            // Do something
        }
    }

    public static void main(String[] args) {
        AnimalSounds s = new VendorSounds(); // Choose vendor
        s.playSound(new LocalCat()); // For example
    }
}

Here "Cat" and "Dog" are vendor-specific settings; I may later change to a French vendor where these two are "Chat" and "Chien", respectively. So to avoid adding vendor-specific information to the LocalType hierarchy which would then have to change each time I change vendors, I hid this mapping in a sort of adapter AnimalSounds (I added VendorSounds as an example for one vendor).

But the cascade of instanceof smells like poor design to me, is there perhaps a more elegant way of accomplishing this which I have overlooked?

Aucun commentaire:

Enregistrer un commentaire