java 选择器设计模式
时间: 2023-07-08 14:50:40 浏览: 57
Java中的选择器设计模式是一种行为型设计模式,它允许你根据一系列条件来选择执行不同的操作。该模式的核心思想是将每个条件与一个命令对象相关联,然后将所有的命令对象存储在一个Map或者List中,最终根据条件来选择对应的命令对象并执行它。
在Java中,选择器设计模式可以通过使用if-else语句、switch语句、策略模式、命令模式、责任链模式等多种方式来实现。其中,使用Map实现选择器模式是一种常见的做法,具体实现可以参考以下示例代码:
```
public class Selector {
private Map<String, Command> commandMap = new HashMap<>();
public void registerCommand(String condition, Command command) {
commandMap.put(condition, command);
}
public void executeCommand(String condition) {
Command command = commandMap.get(condition);
if (command != null) {
command.execute();
} else {
System.out.println("No command registered for " + condition);
}
}
}
public interface Command {
void execute();
}
public class CommandA implements Command {
@Override
public void execute() {
System.out.println("Executing command A");
}
}
public class CommandB implements Command {
@Override
public void execute() {
System.out.println("Executing command B");
}
}
public class Main {
public static void main(String[] args) {
Selector selector = new Selector();
selector.registerCommand("A", new CommandA());
selector.registerCommand("B", new CommandB());
selector.executeCommand("A");
selector.executeCommand("B");
selector.executeCommand("C");
}
}
```
在上述代码中,Selector类就是一个选择器,它用Map来存储各个条件对应的命令对象。registerCommand方法用于注册命令对象,executeCommand方法用于根据条件执行对应的命令对象。Command接口定义了命令对象需要实现的execute方法,CommandA和CommandB就是两个具体的命令对象。最后,在Main方法中,我们向Selector中注册了CommandA和CommandB两个命令对象,并执行了它们,同时也执行了一个未注册的条件。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)