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

时间:2015-07-21 09:04:19

标签: java algorithm abstract-class

我有一个像SendMessageAction这样的孩子的抽象类Action。

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

下面的内容可以帮助您入门。快乐的编码!

<强> Action.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();
   }

}