我最近得到了以下示例,其中我们将操作名称作为字符串传递给方法,然后该方法决定需要调用的函数。
这是解决问题的好方法,还是有更好的方法?
public static final String ACTION_CHARGING_REMINDER = "charging-reminder";
public static void executeTask(Context context, String action) {
if (ACTION_INCREMENT_WATER_COUNT.equals(action)) {
incrementWaterCount(context);
} else if (ACTION_DISMISS_NOTIFICATION.equals(action)) {
NotificationUtils.clearAllNotifications(context);
} else if(ACTION_CHARGING_REMINDER.equals(action)){
issueChargeReminder(context);
}
}发布于 2018-05-15 09:35:02
我会做这样的事情。这可以扩展到你想要的程度,很明显这只是一个例子:
static abstract class ActionHandler {
private String action;
public ActionHandler(String action) {
this.action = action;
}
public boolean canHandleAction(String input) {
return this.action.equals(input);
}
public abstract void handleAction();
}
static class OneActionHandler extends ActionHandler {
public OneActionHandler(String action) {
super(action);
}
@Override
public void handleAction() {
//...
}
}
static class TwoActionHandler extends ActionHandler {
public TwoActionHandler(String action) {
super(action);
}
@Override
public void handleAction() {
//...
}
}
static class Test {
private ActionHandler[] handlers;
public Test() {
handlers = new ActionHandler[]{new OneActionHandler("action1"), new TwoActionHandler("action2")};
}
public void handleAction(String action) {
for(ActionHandler i : handlers) {
if(i.canHandleAction(action)) {
i.handleAction();
break;
}
}
}
}发布于 2018-05-15 18:02:03
这听起来很像react/redux,action/reduction模式。
Reducer指定应用程序的状态如何更改以响应发送到存储的操作。请记住,操作仅描述所发生的事情,而不描述应用程序的状态如何更改。
https://stackoverflow.com/questions/50340942
复制相似问题