Command Pattern - Design Patterns

Web Dev Simplified · Intermediate ·🏗️ Systems Design & Architecture ·6y ago

Key Takeaways

The Command Pattern is demonstrated through the creation of individual commands with perform and undo methods, allowing for decoupling of commands from their implementations and enabling features like undo and redo in applications, utilizing design patterns and systems design principles.

Full Transcript

hello everyone in today's video we're gonna be talking about the command pattern which is one of my favorite patterns because of all of the incredibly cool things it lets you do so let's get started now before we get started I want to talk about today's video sponsor which is Atlantic dotnet hosting and this is an incredible hosting company which is giving you an entire year of hosting completely for free if you sign up with the link down the description below and this isn't some cheapo server this is actually an incredibly powerful server which is more powerful than the server I even host my own website on so you know that this is going to be powerful enough to handle any of your needs on top of that they have incredible reliability and redundancy on their servers so your webpage is always going to be up and always available which is a great thing to know on top of that you're gonna get an additional $50 of free credit if you sign up using the code Kyle so make sure you check that out using the link down in the description below and with that out of the way let's jump into the video you came here for now to get started on the left hand side of my screen I have some really simple code for a calculator that has a value and then we can add subtract multiply and divide and down here I've just added 10 and then divided by 2 and we're getting our output of 10 and then 5 on the right hand side of the screen and every time I say it's going to change so if I divide by 3 for example you see it divides by 3 over here and right now this is not using the command pattern this is just a basic JavaScript class that you're probably all used to now before I go start breaking this down and implementing the command pattern for this calculator I want to talk a little bit about what the command pattern is and why you would even use it and the idea of the command pattern is to take the different operations that you want something to do and encapsulate them into individual commands that have a perform and then an undo method so essentially you can do the operation you can do the command and then you can undo that operation so if we take a look at our calculator here you can see that we have 4 separate commands or operations that we can do on our calculator we can add subtract multiply and then divide these are our different commands and we want to take these commands out of our calculator and actually make them their own objects their own things that have an execute and undo function and the reason for this is that we can actually play back and rewind our commands so that we can add and then we can undo our add which is essentially the same as subtract so we can do and then undo all of our different commands that we want to also we can combine together different commands really easily so if we wanted to add and multiply something normally you'd have to call add and then you'd have to call it multiply it but you could just create a command called add then multiply which will do the adding and the multiplying in the correct order and it'll even undo them in the correct order for you this is the real power of the command pattern the ability to do and then undo as well as to make your commands separate from the actual object that you're doing the command on so to get started let's abstract this ad out into its own command we're just going to create a class for I'm going to call it here the add command and this add command is going to take a constructor and this constructor is just going to take the amount we want to add so I've set a value to add and we'll just set the value to adhere to that value we passed in so now we have a reference to the value to add it's essentially the same thing as the value we passed to the function we're already calling then inside here as I mentioned we need to have an execute function and then we need to have an undo function and this execute function needs to take the current value essentially this dot value because this command is no longer in the calculator it can be used for things that aren't the calculator we could do adding for example in a game we could have some damage calculator that does adding while this could be a calculator on a desktop of a computer they could both still use this add command but they're completely different operations while in the other example if we did like this for the class we would need two different classes to handle those two different types of calculations so now inside this execute like I mentioned it needs to take our current two value and then all we need to do is return our current value plus our value to add and as you remember up here that's very similar to this add function but instead of setting our value we're returning the value since these execute functions are going to be called on anything so we just need to have the result returned so we can actually use that insight that thing we return it to now undo is going to be very similar we need to pass in the current value and we're just doing the current value minus this dot value to add it's the exact same thing is execute just reversed and now what we can do is actually create a new add command so we could say Const add command is equal to new add to command and let's say we wanted to add 10 for example and then in order to execute that we would just say add command dot execute and we would have to pass at the current value of zero for example and if we log this out we should get 10 so let's log that out and make sure we delete all of the code down here and you can see we're getting 10 print it out so we know that our command is working if we change this to 20 it should be 30 and so on and that's great and what we can do even further is we can actually log out the undo operation of that so if we add 10 we want to get the result of that so we'll just put this in a variable we'll say a new value is equal to that so now we have 10 plus 10 so this new value should be 20 what's printed out and then we want to undo with our new value and we should get left back with our original value of 10 and as you can see 20 is what happens when we add the first time and then we undo and we get put back down to 10 now obviously in this trivial case of adding and subtracting having an undo function is pretty useless but when you can think of things such as saving users to a database that's something that having an undo function for is incredibly useful because the undo is really complex but if you just have an undo method and an execute method that makes working with that save functionality really easy so now let's actually look at how we could implement this command inside of our calculator to do that let's just remove this current add command and we're going to add in an execute command function inside of here and this is going to take the command that we want to execute essentially we just need to call that execute function so we can say that our value is going to be equal to our command dot execute with our current value so what this is doing is it's saying take our add command call execute pass it in our current value which in our case is 0 to start with add in that value that we gave to our add command and then set that to our new value so now we have all of our values being properly added with this one execute command function the last thing we need to do is just keep track of all the commands that we've done so we'll just call this our history and we can just say this dot history and what we're going to do is push on that command so now we're actually keeping track of the commands that we've actually executed and we can create here an undo function you just say undo and what this is going to do is it's going to get a command which is going to be our most recent command so we'll just say pop that's going to take the most recent thing off of our array remove it from the array and put it inside this variable then we can just set the value equal to our command dot undo whoops undo and we just need to make sure we pass it in our current value now what we can do is all the way down here we can remove all this code we can go down to our calculator and we can just say calculator oops calculator dot execute command and we want to execute a new add command or we're going to add 10 then we're going to log out the value so we'll set console dot log calculator dot value and this should be 10 if we save we see we get 10 and then let's just try undoing that so we'll say calculator dot undo that's gonna undo whatever the most recent thing was we don't need to keep track of that and then we can just console that log our calculator value and you can see it brought it all the way back down to zero for us and now I could go through and remake every single one of these commands into its own new command so I could remove subtract and multiply and divide but I'm going to do that off camera and come back to you when it's done ok and with that I've removed all of our add subtract divide functions for my calculator we just have execute command and undo and then I've created all of our commands add subtract multiply divide they all are very self-explanatory they just do the operation and then the undo is the opposite of the operation just like the ad was and we can use all these different commands for example we could combine and add in here a multiply command and we could multiply by two and if we say you can see multiplying by two gives us 20 and when we undo it brings us back down to ten because it divides by two but really this kind of looks like a lot of code to do the same thing we were doing before right this is way more complex and way more difficult and you are correct in this very simple instance this is a lot more code it's really not worth the effort but where commands become really useful is the ability to combine commands together and make the save and execute functions of them all just work seamlessly commands ideally start out really small and then build upon themselves to make more complex commands which then build to make even more complex commands and so on until you have one single command that does everything you need to do for a specific instance take for example a button you know when you close most applications a lot of times you're going to get three options you're going to get the option of save oops you're gonna get the option of exit and then you're gonna get the save and exit option and normally if you've implement this without commands you have to write the save functionality inside the save function the exit functionality inside the exit function and you have to duplicate both save and exit inside the save and exit function but with commands we can create a save command we can create an exit command and then our save and exit command just uses both of those commands we don't have to redo any of the logic and the undo is all taken care of it's for us inside that new object so let's actually do that with add and multiply we'll create a class called add then multiply command and inside of it here we're going to do a constructor and it's going to take our value to add as well as our value to multiply and then we're just gonna set those values and then there we go we got the value to add and value to multiply and value to add there we go we actually have those values set and then just like every other command we have an execute and an undo function which are going to take the current value inside of both of these and all we need to do is just execute and undo our commands so up here what we can do is we can actually just change this to a command we can just say add command and we can set that to a new add command where we pass in our value to add just like that we could do the exact same thing but this time for a multiply command and we can do here a new multiply command and of course we're going to pass in the value to multiply now we just have these commands and we can just say that our new value whoops new value is going to be equal to add command make sure you put the bits in front of it this dot add command and all we need to do is call execute with our current value and then we can do the exact same thing but instead of using current value we need to use the new value and we can say the multiply command dot execute with the new value so essentially what we're doing so we're taking our current value we're executing the add command on it and then we're taking the value we get from that and executing the multiply command on it and what we're getting returned here is essentially adding and then multiplying we're combining our two commands together we could do the exact same thing inside of our undo function down here we just need to make sure we undo them in the correct order so we're gonna undo our multiply command by passing it a current value and that's going to be set to our new value whoops just like that so now we have our new value from our undo and then we're just going to return the undo of our add command with that new value just like that and now let's actually use that so right now we're doing add and multiply and it's giving us 20 and then 10 so it's giving us 20 essentially as a result we can do add then multiply make sure we pass with the same parameters of 10 and 2 and we can see that this should be 20 and then it's gonna undo back to 0 and if we say you see it up to 20 and then undoes back down to 0 so you can already see the power of combining together different commands we can even combine a new command with this add then multiply we could have an add then multiply then divide which takes an ad then multiply and a divide command and calls those together you can really combine any commands that you can possibly think of and make any new command out of all of these small commands one place that this command pattern is really popular is in a text editor think about Word documents for example they have a button for bolding text and they have a shortcut for both texts and you also have an undo undo shortcut so you can undo any of these commands so let's say you highlighted some text and bolded it by clicking the bold button you want that bold button to do the exact same thing as the bold shortcut on the keyboard so they both gonna use the same bold command that bold command will have an execute which holds the text that you highlighted and then an undo which essentially just unfolds the text that you originally bolded and both the button and the keyboard shortcut can use the exact same command so it's really easy to hook these things together the real power of the command pattern is the ability to create these small little commands that are completely separate from the thing that implements them in that word document example we didn't have to do an on button click event listener and then put the bold text in there we just had a bold command and gave it to the button same thing with the keyboard shortcut we just gave the bold command to the keyboard shortcut we didn't have to worry about what the bold command was being used for it's just a command and all it knows is that it can be executed and undone and the thing using it just knows that it's a thing that can execute and be undone it doesn't know that it's bold that doesn't know what it is it just knows it's a command so this decoupling is incredibly powerful and the biggest reason to use the command pattern and that's all there is to my favorite pattern the command pattern if you enjoyed the video make sure to check out my other videos in the design pattern series linked over here and subscribe to my channel for more videos just like this thank you very much for watching and have a good day

Original Description

🚨 IMPORTANT: 1 Year Free Hosting: https://www.atlantic.net/webdevsimplified Use code KYLE for an additional $50 The command pattern is probably my favorite design pattern, because of all the fun things you can do with it. The idea of the command pattern is to create an abstraction between the operations an object can do, its commands, and the actual commands themselves. This makes it really easy to combine together or chain different commands without having to change the code. The program can dynamically chain and combine these actions. The best part is since each command is its own object you can easily implement and undo function for each command and make a set of undo-able actions. 📚 Materials/References: GitHub Code: https://github.com/WebDevSimplified/Design-Patterns/tree/master/Command%20Pattern Design Patterns Playlist: https://www.youtube.com/watch?v=BWprw8UHIzA&list=PLZlA0Gpn_vH_CthENcPCM0Dww6a5XYC7f 🧠 Concepts Covered: - What the command pattern is - Why the command pattern is important - How to implement the command pattern in JavaScript - When to use the command pattern 🌎 Find Me Here: My Blog: https://blog.webdevsimplified.com My Courses: https://courses.webdevsimplified.com Patreon: https://www.patreon.com/WebDevSimplified Twitter: https://twitter.com/DevSimplified Discord: https://discord.gg/7StTjnR GitHub: https://github.com/WebDevSimplified CodePen: https://codepen.io/WebDevSimplified #CommandPattern #WDS #DesignPatterns
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Web Dev Simplified · Web Dev Simplified · 0 of 60

← Previous Next →
1 Introduction to Web Development || Setup || Part 1
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
2 Introduction to Web Development || Understanding the Web || Part 2
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
3 Introduction to HTML || Your First Web Page || Part 1
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
4 Introduction to HTML || Basic HTML Elements || Part 2
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
5 Introduction to HTML || Advanced HTML Elements || Part 3
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
6 Introduction to HTML || Links and Inputs || Part 4
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
7 Learn Git in 20 Minutes
Learn Git in 20 Minutes
Web Dev Simplified
8 5 Must Know Sites For Web Developers
5 Must Know Sites For Web Developers
Web Dev Simplified
9 10 Best Visual Studio Code Extensions
10 Best Visual Studio Code Extensions
Web Dev Simplified
10 Learn CSS in 20 Minutes
Learn CSS in 20 Minutes
Web Dev Simplified
11 How to Style a Modern Website (Part One)
How to Style a Modern Website (Part One)
Web Dev Simplified
12 How to Style a Modern Website (Part Two)
How to Style a Modern Website (Part Two)
Web Dev Simplified
13 3D Flip Button Tutorial
3D Flip Button Tutorial
Web Dev Simplified
14 How to Style a Modern Website (Part Three)
How to Style a Modern Website (Part Three)
Web Dev Simplified
15 Animated Loading Spinner Tutorial
Animated Loading Spinner Tutorial
Web Dev Simplified
16 How to Write the Perfect Developer Resume
How to Write the Perfect Developer Resume
Web Dev Simplified
17 Animated Text Reveal Tutorial
Animated Text Reveal Tutorial
Web Dev Simplified
18 Learn Flexbox in 15 Minutes
Learn Flexbox in 15 Minutes
Web Dev Simplified
19 Custom Checkbox Tutorial
Custom Checkbox Tutorial
Web Dev Simplified
20 Start Contributing to Open Source (Hacktoberfest)
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
21 JavaScript Shopping Cart Tutorial for Beginners
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
22 Responsive Video Background Tutorial
Responsive Video Background Tutorial
Web Dev Simplified
23 1,000 Subscriber Giveaway
1,000 Subscriber Giveaway
Web Dev Simplified
24 How To Prevent The Most Common Cross Site Scripting Attack
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
25 Transparent Login Form Tutorial
Transparent Login Form Tutorial
Web Dev Simplified
26 The Forgotten CSS Position
The Forgotten CSS Position
Web Dev Simplified
27 How to Code a Card Matching Game
How to Code a Card Matching Game
Web Dev Simplified
28 10 Must Install Visual Studio Code Extensions
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
29 Learn CSS Grid in 20 Minutes
Learn CSS Grid in 20 Minutes
Web Dev Simplified
30 Learn JSON in 10 Minutes
Learn JSON in 10 Minutes
Web Dev Simplified
31 10 Essential Keyboard Shortcuts For Programmers
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
32 What Is The Fastest Way To Load JavaScript
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
33 Differences Between Var, Let, and Const
Differences Between Var, Let, and Const
Web Dev Simplified
34 How To Install MySQL (Server and Workbench)
How To Install MySQL (Server and Workbench)
Web Dev Simplified
35 Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
Web Dev Simplified
36 How To Solve SQL Problems
How To Solve SQL Problems
Web Dev Simplified
37 What Are Design Patterns?
What Are Design Patterns?
Web Dev Simplified
38 Null Object Pattern - Design Patterns
Null Object Pattern - Design Patterns
Web Dev Simplified
39 Your First Node.js Web Server
Your First Node.js Web Server
Web Dev Simplified
40 How To Setup Payments With Node.js And Stripe
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
41 How To Learn Any New Programming Skill Fast
How To Learn Any New Programming Skill Fast
Web Dev Simplified
42 Asynchronous Vs Synchronous Programming
Asynchronous Vs Synchronous Programming
Web Dev Simplified
43 JavaScript ES6 Arrow Functions Tutorial
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
44 Are You Too Old To Learn Programming?
Are You Too Old To Learn Programming?
Web Dev Simplified
45 JavaScript Cookies vs Local Storage vs Session Storage
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
46 JavaScript Promises In 10 Minutes
JavaScript Promises In 10 Minutes
Web Dev Simplified
47 Builder Pattern - Design Patterns
Builder Pattern - Design Patterns
Web Dev Simplified
48 JavaScript == VS ===
JavaScript == VS ===
Web Dev Simplified
49 JavaScript ES6 Modules
JavaScript ES6 Modules
Web Dev Simplified
50 8 Must Know JavaScript Array Methods
8 Must Know JavaScript Array Methods
Web Dev Simplified
51 CSS Variables Tutorial
CSS Variables Tutorial
Web Dev Simplified
52 JavaScript Async Await
JavaScript Async Await
Web Dev Simplified
53 How To Choose Your First Programming Language
How To Choose Your First Programming Language
Web Dev Simplified
54 Easiest Way To Work With Web Fonts
Easiest Way To Work With Web Fonts
Web Dev Simplified
55 Singleton Pattern - Design Patterns
Singleton Pattern - Design Patterns
Web Dev Simplified
56 Responsive Navbar Tutorial
Responsive Navbar Tutorial
Web Dev Simplified
57 CSS Progress Bar Tutorial
CSS Progress Bar Tutorial
Web Dev Simplified
58 Learn GraphQL In 40 Minutes
Learn GraphQL In 40 Minutes
Web Dev Simplified
59 What is an API?
What is an API?
Web Dev Simplified
60 Learn How To Build A Website In 1 Hour!
Learn How To Build A Website In 1 Hour!
Web Dev Simplified

The Command Pattern is a design pattern that allows for decoupling of commands from their implementations, enabling features like undo and redo in applications. It is demonstrated through the creation of individual commands with perform and undo methods, utilizing design patterns and systems design principles.

Key Takeaways
  1. Create a class for the command
  2. Define a constructor for the command
  3. Implement an execute function for the command
  4. Implement an undo function for the command
  5. Create a history array to keep track of commands
  6. Use commands to combine and execute multiple operations
💡 The Command Pattern is powerful due to its ability to create small, separate commands that can be easily combined and reused.

Related Reads

📰
What absolutely cannot happen: designing systems by their failure boundaries
Learn to design systems by understanding their failure boundaries and how to prioritize robustness over perfection
Medium · Machine Learning
📰
What absolutely cannot happen: designing systems by their failure boundaries
Learn to design systems by considering their failure boundaries for more robust and reliable outcomes
Medium · Data Science
📰
Class, Record ou Struct? Entenda de uma vez quando usar cada um no C#
Learn when to use Class, Record, or Struct in C# for efficient programming
Medium · Programming
📰
UE 5.8 Turns No-Install Unreal Into an Infrastructure Decision
Unreal Engine 5.8 requires infrastructure decisions for no-install 3D due to performance and billing concerns
Medium · Programming
Up next
How To Install iOS 27 Beta on iPhone for FREE! (Step-by-Step)
Ksk Royal
Watch →