DEV Community

BhargavMantha
BhargavMantha

Posted on

Design Pattern in TypeScript: Command Pattern

## Pattern Sub-class

Behavioral Design Patterns-
Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.

Defination

Encapsulate a request as an object, thereby letting you parametrize clients with different requests, and support undoable operations.

It turns a request into a stand-alone object that contains all the information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.

Psudo Names

Actions, Transaction

Why

  1. Consider you are building a text-editor app. You want to create a user interface toolkit that includes objects like buttons and menus that carry out a request in response to user input.
  2. Only applications that use the tool kit know what should be done on which object.
  3. As toolkit designers we have no way of knowing the receiver of the request or the operation that it will carry out.

You have a generic Button class that can be used on the toolbar, as well as for generic buttons in various toolbars.

Though all these buttons look similar they perform different things.

text-editor and button class

THE SIMPLEST SOLUTION IS TO CREATE TONS OF SUB-CLASSES FOR EACH PLACE THE BOTTON IS USED. THE SUBCLASSES WOULD HAVE TO CONTAIN CODE TO BE EXECUTED ON A BUTTON CLICK

sub classing

So what is wrong with this approach

  1. You have an enormous number of subclasses
  2. code will break in a subclass in case of modification of base Button class
  3. some operation logic such as copying/pasting in this case of text editor would need to be invoked from multiple places:
  • User clicks the copy button on the toolbar or copies something using CTRL+C or CMD+C

Why not worth the hassle of subc-lassing

Solution

  1. Separation of Concerns
  2. break the app into multiple layers

request response architecture

The command pattern intuitively says that send the request by extracting all the requirements for making the decision such as the object being called the name of the method and the list of arguments into a single command class with the single method that triggers the request.

The command architucture:

command architucture

The next step is to make your commands implement the same interface. Usually, it has just a single execution method that takes no parameters. This interface lets you use various commands with the same request sender, without coupling it to concrete classes of commands. As a bonus, now you can switch command objects linked to the sender, effectively changing the sender’s behavior at runtime.

Command Architecture

Example Code:

In case the above does not load :
Stack Blits editor url

Stack Blits application url

Top comments (0)