定义Command接口

public interface Command {
    void execute();
}

定义Receiver

@Component
public class Light {

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

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

实现Command

实现SwitchOnCommand

public class SwitchOnCommand implements Command{
    private final Light light;

    public SwitchOnCommand(Light light) {
        this.light = light;
    }

    @Override // Command
    public void execute() {
        light.turnOn();
    }
}

实现SwitchOffCommand

public class SwitchOffCommand implements Command {
    private final Light light;

    public SwitchOffCommand(Light light) {
        this.light = light;
    }

    @Override // Command
    public void execute() {
        light.turnOff();
    }
}

配置Bean

@Configuration
public class MultiBeanConf {

    @Bean(name = "lightOff")
    Command getSwitchOffCommand(@Autowired Light light){
        return new SwitchOffCommand(light);
    }

    @Bean(name = "lightOn")
    Command getSwitchOnCommand(@Autowired Light light){
        return new SwitchOnCommand(light);
    }

}

实现Invoker

@Service
public class SwitchInvoker {
    @Autowired
    Map<String,Command> commandMap;

    public void invoke(String commandName){
        commandMap.get(commandName).execute();
    }

}

测试

@SpringBootTest
class CommandApplicationTests {

	@Autowired
	private SwitchInvoker switchInvoker;

	@Test
	public void switchInvokerTest(){
		switchInvoker.invoke("lightOn");
		switchInvoker.invoke("lightOff");
	}
}

代码地址

github

参考资料

  • https://stackoverflow.com/questions/2140316/java-command-pattern-spring-remoting-how-to-inject-dependencies-to-comma
  • https://springframework.guru/gang-of-four-design-patterns/command-pattern/

更多推荐