命令的封装,每一个命令都是一个操作。首先请求的一方发出请求要求执行一个操作,然后接收的一方收到请求,并执行操作
一个shell示例
public class LinuxSystem {
public void cd(){
System.out.println("已经切换到主目录");
}
public void ls(){
System.out.println("已经列举出当前目录下所有文件");
}
public void restart(){
System.out.println("开始重启系统");
}
}
public interface ICommand {
void execute();//执行命令
}
public class CdCommand implements ICommand {
private LinuxSystem linuxSystem;//持有真正的命令执行者 Linux 操作系统
public CdCommand(LinuxSystem linuxSystem) {
this.linuxSystem = linuxSystem;
}
@Override
public void execute() {
linuxSystem.cd();//调用真正的执行者来执行命令
}
}
public class LsCommand implements ICommand {
private LinuxSystem linuxSystem;//持有真正的命令执行者 Linux 操作系统
public LsCommand(LinuxSystem linuxSystem) {
this.linuxSystem = linuxSystem;
}
@Override
public void execute() {
linuxSystem.ls();//调用真正的执行者来执行命令
}
}
public class RestartCommand implements ICommand {
private LinuxSystem linuxSystem;//持有真正的命令执行者 Linux 操作系统
public RestartCommand(LinuxSystem linuxSystem) {
this.linuxSystem = linuxSystem;
}
@Override
public void execute() {
this.linuxSystem.restart();//调用真正的执行者来执行命令
}
}
//命令请求类
public class XshellInvoker {
private List<ICommand> commandList = new ArrayList<>();//封装了命令的 list 集合
public XshellInvoker(List<ICommand> commandList) {
this.commandList = commandList;
}
/**
* 执行指定命令
* @param command
*/
public void execute(ICommand command){
command.execute();
}
/**
* 执行命令宏,即执行特定的几个命令组合
*/
public void executeCdAndLs(){
for (ICommand command : commandList){
//只执行特定的命令宏
if (command instanceof LsCommand || command instanceof CdCommand){
command.execute();
}
}
}
public void executeAll(){//执行全部命令
for (ICommand command : commandList){//通过循环的方式执行每一个命令
command.execute();
}
}
}
public class TestCommand {
public static void main(String[] args) {
LinuxSystem linuxSystem = new LinuxSystem();//创建命令真正的执行者
//创建三个命令
List<ICommand> commandList = new ArrayList<>();
commandList.add(new CdCommand(linuxSystem));
commandList.add(new LsCommand(linuxSystem));
commandList.add(new RestartCommand(linuxSystem));
XshellInvoker xshellInvoker = new XshellInvoker(commandList);//初始化命令请求者
xshellInvoker.execute(new LsCommand(linuxSystem));//执行指定命令
System.out.println("------------------------");
xshellInvoker.executeCdAndLs();//指定特定命令宏
System.out.println("------------------------");
xshellInvoker.executeAll();//执行全部命令
}
}
桥接模式、中介者模式、命令模式区别
因为这三种模式有一个共性,都是通过一个中间者来实现解耦,初学者有时候会很容易误解:
桥接模式:注重的是两个维度之间的解耦,一个抽象维度,一个实现维度。
中介者模式:注重的是同事对象之间的解耦,各个同事对象是属于同一种类型的平级对象。
命令模式:其侧重的是发送方和请求方,也就是必须要有发送方和请求方才能构成一个完整的整体。像桥接如果缺少某一方只是缺少了功能,但是依然可以正常使用;而中介者就更不用说了,同事多一个少一个在技术上完全不影响。
适用场景
请求调用者和请求接收者需要解耦,使得调用者和接收者不直接互相调用
优点
1.解耦请求与实现
2.拓展方便
3.组合方便
缺点
命令过多,类多