robot scenario - java inheritance, interface types and abstract classes [closed]

北城余情 提交于 2019-12-13 11:27:16

问题


I would like to create a programme based on a robot scenario, that includes abstract classes, interface types and array lists. Can anyone give me some advice on how to create this scenario (via a UML diagram to show how everything links). This scenario needs to include some complex methods, but I am unsure of what to do as a complex method or where to place them in the scenario. Thanks in advance.


回答1:


The world of programming has, for the most part, moved on from complex inheritance hierarchies and instead embraced composition and dependency injection. I suggest you break your monolithic services into small (1-5 method) interfaces. This has the added benefit that unit testing becomes a breeze since you can mock out the dependencies with mockito or similar.

eg:

public interface Walkable {
    void walk(Robot robot, int paces);
}

public interface Talkable {
    void talk(Robot robot, String phrase);
}

public interface Robot {
    void walk(int paces);
    void talk(String phrase);
}

public class RobotImpl implements Robot {
    private final Walkable walkable;
    private final Talkable talkable;

    public RobotImpl(Walkable w, Talkable t) {
        this.walkable = w;
        this.talkable = t;
    }

    public void walk(int paces) {
        walkable.walk(this, paces);
    }

    public void talk(String phrase) {
        talkable.talk(this, phrase);
    }
}


来源:https://stackoverflow.com/questions/27961847/robot-scenario-java-inheritance-interface-types-and-abstract-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!