How to deal with Java Polymorphism in Service Oriented Architecture

前端 未结 5 2170
情歌与酒
情歌与酒 2020-12-28 18:42

What is the path of least evil when dealing with polymorphism and inheritance of entity types in a service-oriented architecture?

A principle of SOA (as I understand

5条回答
  •  北海茫月
    2020-12-28 19:18

    It took me a while from reading this to work out what you were really asking for.

    My interpretation is that you have a set of POJO classes where when passed to a service you want the service to be able to perform different operations depending on the the particular POJO class passed to it.

    Usually I'd try and avoid a wide or deep type hierarchy and deal with instanceof etc. where the one or two cases are needed.

    When for whatever reason there has to be a wide type hierarchy I'd probably use a handler pattern kind of like below.

    class Animal {
    
    }
    class Cat extends Animal {
    
    }
    
    interface AnimalHandler {
        void handleAnimal(Animal animal);
    }
    
    class CatHandler implements AnimalHandler {
    
        @Override
        public void handleAnimal(Animal animal) {
            Cat cat = (Cat)animal;
            // do something with a cat
        }
    
    }
    
    class AnimalServiceImpl implements AnimalHandler {
        Map animalHandlers = new HashMap();
    
        AnimalServiceImpl() { 
            animalHandlers.put(Cat.class, new CatHandler());
        }
        public void handleAnimal(Animal animal) {
            animalHandlers.get(animal.getClass()).handleAnimal(animal);
        }
    }
    

提交回复
热议问题