不要使用Map 来存储动作的属性(name 和nextAction),而是创建由这些属性组成的您自己的类型:
class Action {
private String name;
//nextAction
public void perform() {
//do current action
//use nextAction to perform the next action
}
}
nextAction 现在可以作为对下一个操作的引用:
abstract class Action implements Action {
private String name;
private Action nextAction;
public Action(String name) {
this.name = name;
}
public final void perform() {
perform(name);
nextAction.perform();
}
protected abstract void perform(String name);
}
您现在可以通过子类型 Action 类来创建您的操作:
class CreateFirstName extends Action {
public CreateFirstName(Action nextAction) {
super("CreateFirstName", nextAction);
}
protected final void perform(String name) {
System.out.println("Performing " + name);
}
}
并将它们链接在一起:
Action action = new CreateFirstName(new CreateLastName(new CreateEmail(...)));
嵌套表达式可能会变得非常混乱,但我们稍后会讨论。这里有一个更大的问题。
action4 没有 nextAction,因为它是最后一个动作,但给它一个 nextAction 可能更容易,它是没有下一步动作的占位符
同样的问题也适用于上面的代码。
现在,由于构造函数Action(String, Action),每个动作必须有一个下一个动作。我们可以采取简单的路线并传入一个占位符以表示没有下一步操作(null 是最简单的路线):
class End extends Action {
public End() {
super("", null);
}
}
然后做一个空检查:
//class Action
public void perform() {
perform(name);
if(nextAction != null) {
nextAction.perform(); //performs next action
}
}
但这将是一个code smell。您可以在此处停止阅读并使用简单的修复方法,或者继续下面的更多参与(和教育)路线。
当您使用 null 时,很有可能会成为代码异味的受害者。虽然它并不适用于所有情况(由于 Java 的 null 安全性差),但您应该尝试avoid null if possible。相反,请重新考虑您的设计,如本例所示。如果一切都失败了,请使用Optional。
最后一个动作与其他动作不同。它仍然可以像其他一样执行,但它有不同的属性要求。
这意味着它们可以共享相同的行为抽象,但在定义属性时必须有所不同:
interface Action {
void perform();
}
abstract class ContinuousAction implements Action {
private String name;
private Action nextAction;
public ContinuousAction(String name) {
this.name = name;
}
public final void perform() {
perform(name);
nextAction.perform();
}
protected abstract void perform(String name);
}
abstract class PlainAction implements Action {
private String name;
public PlainAction(String name) {
this.name = name;
}
public final void perform() {
perform(name);
}
protected abstract void perform(String name);
}
最后一个动作将扩展PlainAction,而其他动作将扩展ContinuousAction。
最后,防止长链:
new First(new Second(new Third(new Fourth(new Fifth(new Sixth(new Seventh(new Eighth(new Ninth(new Tenth())))))))))
您可以在每个具体动作中指定下一个动作:
class CreateFirstName extends ContinuousAction {
public CreateFirstName() {
super("CreateFirstName", new CreateLastName());
}
//...
}
class CreateLastName extends ContinuousAction {
public CreateLastName() {
super("CreateLastName", new CreateEmail());
}
//...
}
class CreateEmail extends PlainAction {
public CreateEmail() {
super("CreateEmail");
}
//...
}
ContinuousAction 和 PlainAction 可以进一步抽象。它们都是命名动作(它们有名称),并且该属性以 samw 方式影响它们的contract(将其传递给template methodprocess(String)):
abstract class NamedAction implements Action {
private String name;
public NamedAction(String name) {
this.name = name;
}
public final void perform() {
perform(name);
}
protected abstract void perform(String name);
}
//class ContinuousAction extends NamedAction
//class PlainAction extends NamedAction