15) Command pattern

发布时间 2023-06-09 13:41:41作者: zno2

类别:

 Behavioral Pattern

问题:

 

方案:

 

示例:

 

import java.util.ArrayList;
import java.util.List;

public class CommandPatternDemo {
    public static void main(String[] args) {
        // Check number of arguments
        if (args.length != 1) {
            System.err.println("Argument \"ON\" or \"OFF\" is required.");
            System.exit(-1);
        }

        Light lamp = new Light();

        Command switchUp = new FlipUpCommand(lamp);
        Command switchDown = new FlipDownCommand(lamp);

        Switch mySwitch = new Switch();

        switch (args[0]) {
        case "ON":
            mySwitch.storeAndExecute(switchUp);
            break;
        case "OFF":
            mySwitch.storeAndExecute(switchDown);
            break;
        default:
            System.err.println("Argument \"ON\" or \"OFF\" is required.");
            System.exit(-1);
        }
    }
}

interface Command {
    void execute();
}

class Switch {
    private List<Command> history = new ArrayList<Command>();

    public void storeAndExecute(Command cmd) {
        this.history.add(cmd); // optional
        cmd.execute();
    }
}

class Light {

    public void turnOn() {
        System.out.println("The light is on");
    }

    public void turnOff() {
        System.out.println("The light is off");
    }
}

class FlipUpCommand implements Command {
    private Light theLight;

    public FlipUpCommand(Light light) {
        this.theLight = light;
    }

    @Override
    public void execute() {
        theLight.turnOn();
    }
}

class FlipDownCommand implements Command {
    private Light theLight;

    public FlipDownCommand(Light light) {
        this.theLight = light;
    }

    @Override
    public void execute() {
        theLight.turnOff();
    }
}

 

应用:

 

不足:(

 

优化:)