Android的開發之&java23中設計模式------命令模式

public class Receiver {
    public void action(){
        System.out.print("command");
    }
}



/**
 * Created by Administrator on 2017-10-11.
 * 命令接口
 */

public interface Command {
    public void exe();
}
/**
 * Created by Administrator on 2017-10-11.
 * 命令類實現了Command接口
 */

public class MyCommand implements Command {
    private Receiver receiver;

    public MyCommand(Receiver receiver){
        this.receiver=receiver;
    }

    @Override
    public void exe() {
        receiver.action();
    }
}




/**
 * Created by Administrator on 2017-10-11.
 * 調用者(司令)
 */

public class Invoker {
    private Command command;//命令

    public Invoker(Command command){
        this.command=command;
    }
    //動作
    public void action(){
        command.exe();
    }
}
/**
 * 命令模式(Command)
 */
public class CommandMethodActivity extends AppCompatActivity {
    /**
     * 司令員下令讓士兵去幹件事情,從整個事情的角度來考慮,司令員的作用是,發出口令,口令經過傳遞,
     * 傳到了士兵耳朵裏,士兵去執行。這個過程好在,三者相互解耦,任何一方都不用去依賴其他人,
     * 只需要做好自己的事兒就行,司令員要的是結果,不會去關注到底士兵是怎麼實現的。
     * @param savedInstanceState
     */
//      Invoker是調用者(司令員),Receiver是被調用者(士兵),MyCommand是命令,
//      實現了Command接口,持有接收對象,
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_command_method);

        Receiver receiver=new Receiver();
        Command cmd=new MyCommand(receiver);

        Invoker invoker=new Invoker(cmd);
        invoker.action();
    }
}
github地址:https://github.com/zyj18410105150/DesignMode

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