command模式–java實現 (將軍發出指令樣本)

來源:互聯網
上載者:User
package ParttenDesign;//將軍的命令介面public interface Command {  void defend();  void attack();}

將軍想士兵發出的指令動作

package ParttenDesign;public class Commander implements Command {Command command;public Commander(Command command){this.command=command;}@Overridepublic void attack() {System.out.println("司令發出攻擊命令");command.attack();}@Overridepublic void defend() {System.out.println("司令發出防守命令");command.defend();}}

士兵接受到將軍發出指令後的相應操作

package ParttenDesign;public class Privates implements Command {@Overridepublic void attack() {System.out.println("士兵接受到攻擊命令,發出攻擊");System.out.println("---------------------------------------");System.out.println("");}@Overridepublic void defend() {System.out.println("士兵接受到防守命令,撤退防守");System.out.println("---------------------------------------");System.out.println("");}}

測試代碼:

package ParttenDesign;public class MyMain {/** * 命令模式: * (動作發出者)司令通過(動作的傳遞著)電話發出(防守,攻擊)(指令)命令,(動作接受者)士兵接受命令後作出相應的具體動作 * @param args */public static void main(String[] args) {Command privates=new Privates();Command commander=new Commander(privates);commander.attack();commander.defend();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.