如何创建一个类以捕获具有不同参数类型的命令?
捕获具有类似自变量类型的命令以通过摆动来操作门对象(Swing, DoorNo, swingAngle),我将创建一个如下的类;

class DoorCommand {
     private String commandName;
     private int doorNo;
     private float swingAngle;

     public DoorCommand (String cmdName, int doorNo, float swing angle) {
        // set values here
     }

     // do all the setter and getter here
}


我的问题是,我需要通过使用(Lock, ENABLE/DISABLE)作为参数来启用和禁用门锁。如何在我的DoorCommand班级中容纳这个?我希望能够将DoorCommands存储在列表中; List<DoorCommand> doorCommands = new ArrayList<DoorCommand>();

最佳答案

您可能想签出Command Pattern,它允许您将每个命令创建为公共接口的子类,因此可以将这些命令存储在列表中以用于历史记录或撤消目的。在您的情况下:

// The basic interface for all door commands
public interface DoorCommand {
    public void execute(Door door) throws CommandException;
}

// The Door class is the recipient for all commands
public class Door {
    private List<Command> history = new ArrayList<Command>();
    private int angle;
    private boolean locked;

    public void addCommandToHistory(Command command) {
        history.add(command);
    }

    // Getters and setters.
}

// The command to open the door
public class OpenDoor implements DoorCommand {
    public void execute(Door door) throws CommandException {
        door.addCommandToHistory(this);
        if (door.isLocked()) {
            throw new CommandException("Door is locked, cannot open");
        }
        if (door.getAngle() < 90) {
            door.setAngle(90);
        }
    }
}

// Another command, LockDoor
public class LockDoor implements DoorCommand {
    public void execute(Door door) throws CommandException {
        door.addCommandToHistory(this);
        door.setLocked(true);
    }
}


然后,您可以使用以下命令:

public void operateDoor() {
    Door door = new Door();
    new LockDoor().execute(door);
    new OpenDoor().execute(door);
}


或者,您可以使用构造函数将Door对象传递给命令。

10-01 09:25