Command Pattern in JavaThe command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations. The definition is a bit confusing at first but let's step through it. In analogy to our problem above remote control is the client and stereo, lights etc. are the receivers. In command pattern there is a command object that encapsulates a request by binding together a set of actions on a specific receiver. It does so by exposing just one method execute() that causes some actions to be invoked on the receiver. Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on stereo or may be open the garage door. queue or log requests, and support undoable operations means that Command's Execute operation can store state for reversing its effects in the Command itself. The Command may have an added un Execute operation that reverses the effects of a previous call to execute. It may also support logging changes so that they can be reapplied in case of a system crash. RemoteControlTest.java Output: Light is on Stereo is on Stereo is set for CD input Stereo volume set to 11 Stereo is off Command Pattern Important Points
Benefits of Command Pattern
The command pattern is a powerful and versatile design pattern that can be used to solve a variety of problems. It is a good choice for applications where we need to decouple the client from the receiver, implement undo/redo functionality, or implement queuing functionality. Next TopicCSV to List Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India