Behavioural Design Pattern: Command Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Behavioural Design Pattern: Command Pattern

Share This
"Encapsulate a request within an object as a command and pass it to the invoker object," states a Command Pattern. The invoker object locates the suitable object capable of processing the given command, transfers it to that object, and that object carries out the requested action.

It is also referred to as a transaction or action.

The benefit of command pattern
  • It creates a separation between the object that initiates the operation and the object that executes it. 
  • It facilitates the addition of new commands by preserving the integrity of existing classes.

Implementing a command pattern:
  • When parameterizing objects in response to an action executed. 
  • When it is necessary to generate and execute requests at dissimilar moments. 
  • When rollback, logging, or transaction functionality must be supported.

 Command.java 
package com.t4b.test.java.dp.bp.cp; interface Command { void execute(); }
 MouseCommands.java 
package com.t4b.test.java.dp.bp.cp; import java.util.ArrayList; import java.util.List; 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(); } }
 MouseCursor.java 
package com.t4b.test.java.dp.bp.cp; 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; } }
 MoveCursor.java 
package com.t4b.test.java.dp.bp.cp; class MoveCursor implements Command { private MouseCursor abcStock; public MoveCursor(MouseCursor abcStock) { this.abcStock = abcStock; } public void execute() { abcStock.move(); } }
 ResetCursor.java 
package com.t4b.test.java.dp.bp.cp; class ResetCursor implements Command { private MouseCursor abcStock; public ResetCursor(MouseCursor abcStock) { this.abcStock = abcStock; } public void execute() { abcStock.reset(); } }
 TestMain.java 
package com.t4b.test.java.dp.bp.cp; public class TestMain { 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(); } }

Happy Exploring!

No comments:

Post a Comment