android設計模式二十三式(十八)——命令模式(Command)

命令模式

命令模式,主要作用是將命令的發起者和命令的執行者進行解耦。

舉個栗子:

返點到了,你媽媽喊你回家吃飯咯,那麼這個命令的發起者就是你媽媽,你而你就是那個回家吃飯的命令執行者

/**
 * @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來進行命令傳遞並調用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章