【设计模式】Spring Boot中实践命令模式

本文介绍了如何在Spring Boot中应用命令模式,包括定义Command接口、创建Receiver、实现不同类型的Command(如SwitchOnCommand和SwitchOffCommand)、配置Bean、设计Invoker以及进行测试。提供了代码仓库链接和相关参考资料。

定义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/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值