使用访客模式。
您的命令有一个接受 aDoor
并对其进行操作的方法。
你遍历你的DoorCommand
对象并发送每个对象Door
,它会做它想做的事情。
这样,您的DoorCommand
逻辑与逻辑分离,Door
并且您不需要一个庞大的DoorCommand
类来实现所有可能的命令。
这是一个简单的例子:
static class Door {
private final String name;
public Door(String name) {
this.name = name;
}
public void accept(final DoorVisitor visitor) {
visitor.visit(this);
}
@Override
public String toString() {
return name;
}
}
static interface DoorVisitor {
void visit(Door door);
}
static class SwingCommand implements DoorVisitor {
private final float swingAngle;
public SwingCommand(float swingAngle) {
this.swingAngle = swingAngle;
}
@Override
public void visit(Door door) {
System.out.printf("Swing door %s by %s%n", door, swingAngle);
}
}
static class LockCommand implements DoorVisitor {
private boolean locked;
public LockCommand(boolean locked) {
this.locked = locked;
}
@Override
public void visit(Door door) {
System.out.printf("Door %s is locked: %s%n", door, locked);
}
}
public static void main(String[] args) throws Exception {
final Door door = new Door("Front Door");
final List<DoorVisitor> commands = new LinkedList<>();
commands.add(new SwingCommand(0));
commands.add(new LockCommand(true));
for (final DoorVisitor c : commands) {
door.accept(c);
}
}