How to deal with Java Polymorphism in Service Oriented Architecture

前端 未结 5 2171
情歌与酒
情歌与酒 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:13

    Having thought about this a bit more I've thought on an alternative approach that makes for a simpler design.

    abstract class Animal {
    }
    
    class Cat extends Animal {
        public String meow() {
            return "Meow";
        }
    }
    
    class Dog extends Animal {
        public String  bark() {
            return "Bark";
        }
    }
    
    class AnimalService { 
        public String getSound(Animal animal) {
            try {
                Method method = this.getClass().getMethod("getSound", animal.getClass());
                return (String) method.invoke(this, animal);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        public String getSound(Cat cat) {
            return cat.meow();
        }
        public String getSound(Dog dog) {
            return dog.bark();
        }
    }
    
    public static void main(String[] args) {
        AnimalService animalService = new AnimalService();
        List animals = new ArrayList();
        animals.add(new Cat());
        animals.add(new Dog());
    
        for (Animal animal : animals) {
            String sound = animalService.getSound(animal);
            System.out.println(sound);
        }
    }
    

提交回复
热议问题