W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
命令模式是數據驅動設計模式它是行為模式之一。
請求被作為命令的對象包裝傳遞給invoker對象。
Invoker對象將命令傳遞到相應的對象并且該對象執(zhí)行該命令。
import java.util.ArrayList; import java.util.List; interface Command { void execute(); } class MouseCursor { private int x = 10; private int y = 10; public void move() { System.out.println("Old Position:"+x +":"+y); x++; y++; System.out.println("New Position:"+x +":"+y); } public void reset() { System.out.println("reset"); x = 10; y = 10; } } class MoveCursor implements Command { private MouseCursor abcStock; public MoveCursor(MouseCursor abcStock) { this.abcStock = abcStock; } public void execute() { abcStock.move(); } } class ResetCursor implements Command { private MouseCursor abcStock; public ResetCursor(MouseCursor abcStock) { this.abcStock = abcStock; } public void execute() { abcStock.reset(); } } class MouseCommands { private List<Command> orderList = new ArrayList<Command>(); public void takeOrder(Command order) { orderList.add(order); } public void placeOrders() { for (Command order : orderList) { order.execute(); } orderList.clear(); } } public class Main { public static void main(String[] args) { MouseCursor cursor = new MouseCursor(); MoveCursor moveCursor = new MoveCursor(cursor); ResetCursor resetCursor = new ResetCursor(cursor); MouseCommands commands= new MouseCommands(); commands.takeOrder(moveCursor); commands.takeOrder(resetCursor); commands.placeOrders(); } }
上面的代碼生成以下結果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: