Tuesday, April 5, 2022

SKP's GoF Design Patterns a Day - 09 - Command

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.
 
Command Pattern [Sample Code]
In scenarios, where we need to create a sequence of actions (or operations) and perform them at a specified (later) point in time, we have a candidate for usage of Command Pattern. Though it very closely resembles the Observer pattern in implementation, the usage is different and the command (actions) is invoked only on a single chosen receiver by an invoker, than on all observers.
 
 
Fig. 4 : Command (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


The example is of an Auction House where there are various items for auction, the base abstract class of which is represented by AuctionItem. The abstract method to be implemented by implementing classes is sell(). AuctionVase, AuctionFurniture and AuctionJewel are all concrete implementations of AuctionItem. Instances of each of these are created and set (mapped by an itemKey) into the AuctionControl, which can be thought of as a remote control for presenting items in the AuctionStore. Whenever the presentItem() is invoked on the AuctionControl class, passing in an itemKey, the appropriate AuctionItem instance is selected and sell() is invoked on this instance

No comments: