繁体   English   中英

Java-为抽象类的每个子类强制实现方法

[英]Java - force implementation of a method for each child of an abstract class

我有一个带有SendMessageAction之类的子类的抽象类Action。

我想在服务中运行这些操作,但是如何强制执行每个孩子?

例如,我想实现一个抽象方法:void run(Action action)和每个可能的Action的方法“ run”,如果缺少某些方法,则会出错。

任何想法 ?

如下所示的内容应该可以帮助您入门。 编码愉快!

动作.java

public abstract class Action {
   protected abstract void runAction(); 
}

MessageSenderAction.java

public class MessageSenderAction extends Action {

   public void runAction() {
       //send message
   }

}

SomeOtherAction.java

public class SomeOtherAction extends Action {

   public void runAction() {
       //do something else
   }
}

ActionHandler.java

public class  ActionHandler {

    private final static ActionHandler INSTANCE = new ActionHandler();

    private ActionHandler() {}

    public static ActionHandler getInstance() {
      return INSTANCE;
    }

    private List<Action> allActions = new ArrayList<Action>();


    public void addAction(Action action) {
        allActions.add(action);
    }

    public void runAllActions() {
        for(Action action: allActions) {
            //just to handle exception if there is any. Not to hamper other actions in case of any failures
            try {
                action.runAction();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

ActionDemo.java

public class ActionDemo {

   public static void main(String... args) {

    ActionHandler actionHandler = ActionHandler.getInstance();
    Action msgSenderAction = new MessageSenderAction();
    Action someOtherAction = new SomeOtherAction();
    actionHandler.addAction(msgSenderAction);
    actionHandler.addAction(someOtherAction);
    actionHandler.runAllActions();
   }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM