android设计模式二十三式(十八)——命令模式(Command)

    xiaoxiao2022-07-05  144

    命令模式

    命令模式,主要作用是将命令的发起者和命令的执行者进行解耦。

    举个栗子:

    返点到了,你妈妈喊你回家吃饭咯,那么这个命令的发起者就是你妈妈,你而你就是那个回家吃饭的命令执行者

    /** * @author: hx * @Time: 2019/5/22 * @Description: Command */ public interface Command { /** * 执行命令的方法 */ void excute(); } /** * @author: hx * @Time: 2019/5/22 * @Description: MyCommand */ public class MyCommand implements Command { private You mYou; public MyCommand(You you) { mYou = you; } @Override public void excute() { System.out.println("执行命令"); mYou.action(); } } /** * @author: hx * @Time: 2019/5/22 * @Description: Mother */ public class Mother { private Command mCommand; public Mother(Command command) { mCommand = command; } public void action(){ System.out.println("回家吃饭"); mCommand.excute(); } } /** * @author: hx * @Time: 2019/5/22 * @Description: You */ public class You { private String name; public You(String name) { this.name = name; } public void action(){ System.out.println(name+"回家吃饭"); } }

    来一个喊你回家吃饭

    public static void main(String[] args){ You you = new You("小明"); Command command = new MyCommand(you); Mother mother = new Mother(command); mother.action(); } 输出结果: 回家吃饭 执行命令 小明回家吃饭

    是不是很好理解,其实就是把mother和you分来了,相互之间不直接调用,通过中间的command来进行命令传递并调用。

    最新回复(0)