I used the facade design pattern once to simplify this widget I created. When I generated the Javadoc, I blew my lead's mind as to how simple it was to use. I did not need to create any documentation because there were only a handful of exposed methods and the names of these methods were very explicit.
@LearnAnyCoding-vg6up go read Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four. This book is essentially where the idea of design patterns came from and is seen as the most important book in object oriented programming
It's because most hands on coding are done by junior to mid devs. Senior above mostly just do code reviews. Tech lead above will focus more on the architecture and overall flow of the app. So these low level functional patterns and algorithms knowledge are expected to be lost for higher positions, but expected to be well known by junior to mid devs, and to some extent senior devs. You don't exactly need to memorize all of them but just remember common ones like these 5 and know them well that you know exactly when to implement them, or it just adds unnecessary complexity. Trust me, if you are not being interviewed by HR who has no idea what these are and are just checking for keywords, Tech leads and engineering managers will be already impressed. I do interviews myself and I rarely ask these trivial questions, I'd mostly ask situational questions where you can implement a common design pattern. I'm also more interested in how you work with a team and if you're just doing software engineering for money or software engineering is your passion. It's cliche but people who love what they do are less toxic and wouldn't try to do bare minimum then credit grab from colleagues.
@@thatrandomperson3968 What in gods name are you talking about? I have not worked at a single company ever where junior devs do more coding than senior devs. And tech leads focusing on architecture? That’s what software architects do. Tech leads have next to nothing to do with the actual development process
@@Foxtrot6624 lol where do you think software/tech/solutions architects come from? Hint they start off as junior engineers, after tech lead you branch off to management or architecture. I wonder what kind of industry where a higher position would focus on coding wtf, no wonder you guys are scared of AI, outsourcing and stuff. Being a code monkey is for lower level positions, all SE will eventually end up in architecture or management whether you like it or not, unless of course you're content with senior SE position for the rest of your career then you do you, or you're with a startup where there's only a handful of SE and everyone needs to code. When the org grows you hire more juniors and you will have less and less hands on coding. Even external resources such as senior tech consultants and managing consultants focus more on architecture and design, and handover coding to junior/senior SE. Why do senior devs code less than junior you say? Simply because SSE has much more responsibilities than junior SE 1st. As a senior you are involved in overall design and planning meetings and other shenanigans 2nd you have to do final reviews for mid, junior SE and other senior SE, this means you're reviewing codes of multiple SEs. Unless you just type "lgtm" merge the code and pray, this consumes a lot of your time. 3rd You have to assist other SE when there are issues or bugs it's your responsibility as Senior. With all of these how can an SSE code more than junior SE? When lower level SE just focus entirely on their own tickets and peer reviews. You must understand that the main difference between a junior and senior SE isn't coding proficiency alone, the higher position you are the less involved you are in coding sadly.
Design patterns intertwine throughout my code, mostly without me thinking about it. Dependency Injection is used everywhere and Factory structure is pretty generic, so starting points all have similar structure. I look at the core of each pattern and how they relate to each other. I see Builder in both Strategy and Observer. I see Strategy in Observer, with the relationship changed to one to many (iteration) and any number of "strategies" being active at a time. The Decorator vs Strategy choice is properties vs behavior. And so on.
I agree with you completely about these commonly used patterns. They really are so useful in 'real programming life'. I also agree that it is well worth appreciating the other patterns as they really are useful in specific circumstances. Thanks for this. Appreciated.
One very important aspect of the design patterns is that they depend on the language and its capabilities. This means that in higher-level languages you can implement some of the patterns as algorithms. In this sense, design patterns can be thought of as a relatively good way to go around limitations of your language. As an example, let's take the singleton pattern. It was introduced in book, because there's no way to make it as a library code in C++[1]. But for example in Java[2] you can use a dependency injection library and you can just annotate your class with @Singleton. The library will take care of the rest. Another example where the pattern all but disappears is the strategy pattern. Languages that support higher-order functions can just use them instead of the pattern. ---- [1] Or at least you couldn't at the time. I haven't been following recent C++ development. [2] I don't know enough C# to show similar example, sorry.
in singleton pattern example using Lazy is wrong, value field can be initialized in race conditions. for this scenario can be used static function LazyInitializer.EnsureInitialized(T, Func)
Gee, I remember when objects had their own controllers and "polymorphism" was part of the object and you didn't need a completely separate abstraction to do the work. Yes, I have the "Gang of Four" black-white-and-blue book. They went overboard on abstractions and complicate the crap out of everything.
You managed to make the RUclips "please subscribe" message an integral part of your vid. Well done ;-) . And the rest of the vid too, of course, I'm a CS grad and have read this valueable book thoroughly...
To people from JS/Python like me who were confused about the use-cases of the Strategy Pattern, the simple example shown here don't really fit these languages. In Python/JS it'd be more natural to simply map these functions to the variables or even map them to the methods/strategies names as keys in a dictionary (since JS/Python have functions as first class citizens). However, if these functions need to preserve state, or if they have a lot of shared data between them, then can be used coded as the Strategy Design Pattern.
Thanks for providing some context for Python/JS users. Yes all the examples shown are in C# and would probably be familiar for Java users but don't really work for non OOP languages.
I’ve found that some OO patterns don’t really make sense in Python because of functions being first-class citizens allowing you to pass functions around like a variable, where as other languages are weaker and need these patterns because you can’t simply pass a function. Same thing with Abstract Factory in Python.
Those languages are great because of flexibility. But if you want to enforce certain patterns, then it can be tricky. For JavaScript, try typescript, for python, try abstract base class (abc) library.
OOP: we identified a set of things called patterns so that you could... FP: JUST USE A FUNCTION FOR THAT (half-joking) Now seriously, to me the top used C# patterns are: - iterator (`foreach`) - factory method (a factory interface injected via DI to make you a factory interface to make you a...) - builder (hostBuilder.ConfigureLogging(...).ConfigureServices(...)....) - strategy (which most of the 2nd-order functions implement) - command (every closure is a command with Invoke method) - interpreter (DSLs are nice) I'm not mentioning singleton here because usually such scope is addressed by a DI-container
You could say that the concept of a recipe is a design pattern. It's structured so that it has a list of ingredients, and the method for making the food.
If you do it that way, the lock will be performed every time GetInstance() is called. It will only be null once, so the way it's done in the video will require two locks at the most, probably just one.
@@zo1dbergit's a kind of optimization. Taking a lock is a heavy operation, checking for null before it helps us avoid taking lock every time when we need an instance
God Damn It! Now I want all those cakes. Brings back memories of eating all of those in different parts of the world with friends and family Two mnemonics to remember: "Create Structures and Behave: Single Decorated Faces Observe Strategies" Create Structures and Behave: - Create reminds you of Creational patterns. - Structures points to Structural patterns. - Behave refers to Behavioral patterns. Single Decorated Faces Observe Strategies: - Single stands for Singleton (Creational). - Decorated for Decorator (Structural). - Faces for Facade (Structural). - Observe for Observer (Behavioral). - Strategies for Strategy (Behavioral). I like something more fun, so here we go "Crazy Squirrels Build Dens, Often Strategically" - Crazy hints at Creational patterns. - Squirrels Build Dens points to the Structural patterns. - Often Strategically suggests Behavioral patterns. Within each category: - Single (from Squirrels) for Singleton (Creational). - Build (Beginning of Build) for Decorator and Dens (D of Dens) for Facade (both Structural). - Often for Observer and Strategically for Strategy (both Behavioral).
Thanks for the video. In .NET we have one extension method in service class to add single instance of the class(AddSingleton). Do we still need to use singleton design pattern?
While it's good to know about singletons, you genereally don't want to explicitly codify them. It's almost always best to let your DI container give you one.
Great video. Never heard about the Facade pattern, when you started explaining it I thought it was the Adapter pattern, What's the difference between them?
An adapter can be a function, or class, which acts as a translator between one functions/class output and another's input Facade is more like a nice function, or class, that's easy to use and acts as the main interface/function which hides a lot of ugliness underneath to get things done A facade of a house hides all the details on the inside, but you get a basic idea on what the house is used for by checking it's exterior - it's facade - see a police building for example
A facade doesn't have to be a nice abstraction on top of a mess. It could be you just want to abstract multiple types behind an interface so all types (usually of a third party) look the same, i.e. they have the same facade, to the consumer of them - otherwise the consumer would need to know each implementation. An adapater is about translating something into something else and acts like a middelware between the two things.
@@fifty-plus 💯 That’s when I’ve used a facade pattern in the past - when our application needed to send messages and make calls to outside services, and we knew we’d be swapping out those services over the next few months. All our internal classes called simple, standardized methods on the facade, and we just updated the internals of the facade to handle the various API implementations of the external services. Kind of an adapter as well? But the reason why we did it was to keep things clean and stable over time.
The good thing about a decorator is that it can extend any class. So you write a functionality once and plug it in any class that you want, without duplicating code. You can also use it while extending a class you can't access I think, so you can extend a class while not being able to change anything inside it (the open-closed principle he refers to)
I don't agree with how you described your Strategy pattern with the cakes (but I also don't think you displayed what "GetMethod()" was supposed to do). The example with Google Maps illustrated it well: The context being the various modes of travel, returning the strategy (method) of how to perform the action. To further elucidate, other modifiers to this context could be [additional stops, fastest route, avoid traffic, no tolls, no freeways, etc] which then returns a different, modified strategy (method) of how to get from A->B.
I'm sorry I still did not get it - the prerequisite for the decorator pattern is that one is obliged to use another implementation of the same interface - you just may expand it by putting your extra staff here and there?
Yes, that's exactly how you use the pattern. An example would be a logger. The logger has a certain basic functionality that is the same throughout the entire project. In this example, however, you want to save/output the time and the component in which the message was logged for step A. In step B, the time should not be displayed in the log messages. Instead, the type of the log message (warning, error, info ...) should be displayed there. This behaviour can of course be implemented in many different ways. For example, you could add a timestamp attribute to a log message and specify a flag as to whether the date object should also be displayed. This approach works, of course. And in smaller projects, there is definitely no reason not to use such an approach. However, the more such requirements are added, the more complex the code of the class becomes. This means it is more difficult to extend / maintain / understand the code. With the decorator pattern, the logic required for the individual use cases can only be found in the special decorator. This keeps the basic functionality of the logger tidier and therefore easier to maintain. However, if more similar use cases are added, the Decorator pattern is of course an obstacle. Assuming you simply want to be able to switch the individual extras (time, type, location) on and off and you need each of the 2^3 cases in your project, this would mean that you would have to write 8 Decorators with similar functionality.
Hi, random question out of curiosity. Actually instead of implementing singleton in this way isn't it more common to register as a singleton service via Dependency Injection ? I think I have never encountered it yet being designed like this and maybe it's just me being exposed to the same style on the projects i work on.
In your singleton pattern, why wouldn't you just lock once and check whether the instance is null inside the mutex locked code block? What is the purpose of the instance == null check outside the lock?
@cern1999sb This is called the Double-null check pattern. It eliminates the overhead of acquiring the lock on every method invocation when it's only really needed once.
Great video. As a Java developer I not only use the patterns you mentiond but also Visitor, Factory, Builder and Composite. I think they are very common too.
My opinion: These contrived analogies, such as using cake really don't work when trying to explain something in software. You are explaining to technical developers, not children. In my experience these long winded analogies only distract me from what you are talking about, especially when showing B-roll of cutting very attractive looking cake. Really, only 40% of my attention is on what you are actually trying to say and most is focused on the sweetness, softness and taste of the cake, all of which are very strong distractors.
I have reservations against the singleton pattern. Functional style programming combined with immutability kind of makes it unnecessary. If your code doesn't actually care about the object's reference, only it's value, and that value can never change, the optimizations that result is effectively your singleton, and you didn't even have to write it.
Builder? Used ALL over the .NET Core. Chain of Responsibility - same, plus all the different "Fluent"Something. Factory method - all of the IoC/DI are factories on steroids, Iterator - every collection in .NET...
Desde o vanilla JS eu já evito usar Node, sempre tento forçar Element. Por exemplo, ao invés de pegar o último filho de um elemento com element.lastChild (que inclui todos os Nodes), uso element.lastElementChild (que inclui somente HTMLElements), pois Node pode ser até mesmo os espaços em branco soltos no HTML (por mais que não apareça na tela).
Your objects would be arguments into a constructor public interface IOption {...} class OptionOne : IOption { // some implemention} class OptionTwo : IOption { // some implemention} class MyTool { private readonly _theAction; public MyTool(IOption theAction) { this._theAction = theAction } } Now you can create a tool and assign actions without needing to recompile MyTool toolOne = new MyTool(new OptionOne()); Of course you might add additional things, actions. Like which file formats, checks, reads, etc. Into the tool.
With modern dependency injection a Singleton pattern is very outdated. I personally haven't used it for over 5 years. Moreover, controlling an object lifetime by the object itself seems to conflict with a single responsible principle and would definitely mark a Singleton code down in a code review.
I have only ever heard about singleton patterns discussed in theory. I have never seen that pattern actually be implemented in the wild. Closest thing is managing dependencies and calling addsingleton, addscoped, or addtransient. I think programmers need to get real about just saying things to look smart.
Singleton is an antipattern. It's a violation of SRP and makes unit testing unnecessarily difficult. If you need a singleton object, you should enforce that elsewhere in the code or use dependency injection.
Like many videos and books on design patterns, this videos also fails to meet the most desired objective - to help developers choose the right design pattern when certain situations are presented to them. The fancy names of the patterns and their explanation is great, but if developers are not able to analyze a problem and quickly "map" it to one of these patterns, then it isn't really useful.
The notion of so-called "design patterns" was inherent in even the most early functional languages, e,g. lisp, but they were called "expressions" whose function definitions might or might not contain other expressions! It's not rokit syance, and DEFINATELY not LATTER-DAY object-oriented pseudo-paradigm-ical mumbo-jumbo! Simples, as simple can be! (:-)
Software engineer are not made on websites, you're more a developer, someone learning something very specific, taking a biology course doesn't make you a doctor, what a woke joke
You shouldn't use the observer pattern. You should use the event pattern with an event handler class instead. The observer pattern polls and breaks encapsulation. Event patterns act as an interrupt, thus using less process time and only needs to know that the event handler exists and that there is an object that creates an event that you subscribe to through the event handler. edit: The pattern you've described in the video is the event pattern, and not the observer pattern. Please use the appropriate name.
This video shows a textbook example of the observer pattern. The observer pattern is when a subject maintains a list of its observers and automatically notifies the observers when the subject changes (no polling involved). Using the names Publisher/Subscriber may cause confusion for people familiar with the pub-sub pattern though. As far as I can tell, there's no common pattern called the "event pattern". What are you trying to refer to?
From my understanding the entire point of the observer pattern (right from the Gang of Four) is to avoid polling. I’m wondering if you may have learned the wrong name for the observer pattern?
@@TeenyPort The implementation of the observer pattern I saw was the original small talk implementation from somewhere between the late 70's to the early 90's pre Design Patterns being written, there was a newer version that didn't poll, and then an event pattern that was also available. It made for some rough to follow coding standards. Why I recommend the event pattern is because the observer pattern does break encapsulation by knowing the object being observed has a state you are interested in. The event pattern only requires you to know the object exists, has an event, and there is an event handler object. The object of interest registers with the event handler that it exists and that it has the events it has. The object interested in the events registers its interest in those events from the object. Every object has an event queue. When the object of the events of interest triggers the event it publishes it to the event handler that then distributes it to the subscribed objects. This allows for better debugging process, lowers the risk of operations performing out of order, and removes a variable on all objects of the interested in queue while also allowing multiple actions to be observed improving overall performance. The observer pattern was almost not included in design patterns because of its issues with breaking encapsulation and runtime debugging. I'd say within 5 years of design patterns being published someone invented the event pattern because of all of its superior performance capabilities. The reason it isn't the standard is that every years there are twice as many new programmers entering the job market than the year before so there isn't enough time to develop new programmers and pass on institutional knowledge. Since Design Patterns is the gold standard of how to make a program, even if it is now 30 years old.
Well, if you have DesignPatterns in vid tittle, do you have to keep repeating it every 5 sec?? We got this, rlly - vid is about D-Patterns... Ok chill...
It is always astounding how people who (probably) believe they are professional developers get all excited about trivial videos like these. Nothing wrong with the video, but ... really?
Ah yes I too am very smart and professional because I know all my patterns.. clearly I was born this way and never had to learn anything like those puny unprofessionals...?
I used the facade design pattern once to simplify this widget I created. When I generated the Javadoc, I blew my lead's mind as to how simple it was to use. I did not need to create any documentation because there were only a handful of exposed methods and the names of these methods were very explicit.
Just stumbled upon this channel and as a new dev, I'm loving the bite-sized videos that each explain a useful concept / topic!
But you need to know 100 design patterns at interview for a junior position
@LearnAnyCoding-vg6up go read Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four. This book is essentially where the idea of design patterns came from and is seen as the most important book in object oriented programming
@LearnAnyCoding-vg6up I think he was pointing out that interviews select across a potentially huge number of design patterns.
It's because most hands on coding are done by junior to mid devs. Senior above mostly just do code reviews. Tech lead above will focus more on the architecture and overall flow of the app. So these low level functional patterns and algorithms knowledge are expected to be lost for higher positions, but expected to be well known by junior to mid devs, and to some extent senior devs.
You don't exactly need to memorize all of them but just remember common ones like these 5 and know them well that you know exactly when to implement them, or it just adds unnecessary complexity. Trust me, if you are not being interviewed by HR who has no idea what these are and are just checking for keywords, Tech leads and engineering managers will be already impressed.
I do interviews myself and I rarely ask these trivial questions, I'd mostly ask situational questions where you can implement a common design pattern. I'm also more interested in how you work with a team and if you're just doing software engineering for money or software engineering is your passion. It's cliche but people who love what they do are less toxic and wouldn't try to do bare minimum then credit grab from colleagues.
@@thatrandomperson3968 What in gods name are you talking about? I have not worked at a single company ever where junior devs do more coding than senior devs. And tech leads focusing on architecture? That’s what software architects do. Tech leads have next to nothing to do with the actual development process
@@Foxtrot6624 lol where do you think software/tech/solutions architects come from? Hint they start off as junior engineers, after tech lead you branch off to management or architecture. I wonder what kind of industry where a higher position would focus on coding wtf, no wonder you guys are scared of AI, outsourcing and stuff.
Being a code monkey is for lower level positions, all SE will eventually end up in architecture or management whether you like it or not, unless of course you're content with senior SE position for the rest of your career then you do you, or you're with a startup where there's only a handful of SE and everyone needs to code. When the org grows you hire more juniors and you will have less and less hands on coding.
Even external resources such as senior tech consultants and managing consultants focus more on architecture and design, and handover coding to junior/senior SE.
Why do senior devs code less than junior you say? Simply because SSE has much more responsibilities than junior SE
1st. As a senior you are involved in overall design and planning meetings and other shenanigans
2nd you have to do final reviews for mid, junior SE and other senior SE, this means you're reviewing codes of multiple SEs. Unless you just type "lgtm" merge the code and pray, this consumes a lot of your time.
3rd You have to assist other SE when there are issues or bugs it's your responsibility as Senior.
With all of these how can an SSE code more than junior SE? When lower level SE just focus entirely on their own tickets and peer reviews.
You must understand that the main difference between a junior and senior SE isn't coding proficiency alone, the higher position you are the less involved you are in coding sadly.
Thank you for taking the time to make this video. Much appreciated.
Design patterns intertwine throughout my code, mostly without me thinking about it. Dependency Injection is used everywhere and Factory structure is pretty generic, so starting points all have similar structure. I look at the core of each pattern and how they relate to each other. I see Builder in both Strategy and Observer. I see Strategy in Observer, with the relationship changed to one to many (iteration) and any number of "strategies" being active at a time. The Decorator vs Strategy choice is properties vs behavior. And so on.
I agree with you completely about these commonly used patterns. They really are so useful in 'real programming life'. I also agree that it is well worth appreciating the other patterns as they really are useful in specific circumstances. Thanks for this. Appreciated.
Thank you for making this. I'm very hands on and have definitely used these before without even realising what they were called.
One very important aspect of the design patterns is that they depend on the language and its capabilities. This means that in higher-level languages you can implement some of the patterns as algorithms. In this sense, design patterns can be thought of as a relatively good way to go around limitations of your language.
As an example, let's take the singleton pattern. It was introduced in book, because there's no way to make it as a library code in C++[1]. But for example in Java[2] you can use a dependency injection library and you can just annotate your class with @Singleton. The library will take care of the rest.
Another example where the pattern all but disappears is the strategy pattern. Languages that support higher-order functions can just use them instead of the pattern.
----
[1] Or at least you couldn't at the time. I haven't been following recent C++ development.
[2] I don't know enough C# to show similar example, sorry.
in singleton pattern example using Lazy is wrong, value field can be initialized in race conditions. for this scenario can be used static function LazyInitializer.EnsureInitialized(T, Func)
Class init in .Net is thread-safe, so no issue there
Even Lazy is not required unless you really need lazy init
Gee, I remember when objects had their own controllers and "polymorphism" was part of the object and you didn't need a completely separate abstraction to do the work. Yes, I have the "Gang of Four" black-white-and-blue book. They went overboard on abstractions and complicate the crap out of everything.
You managed to make the RUclips "please subscribe" message an integral part of your vid. Well done ;-) . And the rest of the vid too, of course, I'm a CS grad and have read this valueable book thoroughly...
I use strategy pattern all the time. Such an important one for clean code.
the back to the future time machine configurations are so cool
oh wow, im using strategy + factory + facade pattern unknowingly when implementing AES cipher since its have ECB, GCM, and CBC
To people from JS/Python like me who were confused about the use-cases of the Strategy Pattern, the simple example shown here don't really fit these languages. In Python/JS it'd be more natural to simply map these functions to the variables or even map them to the methods/strategies names as keys in a dictionary (since JS/Python have functions as first class citizens).
However, if these functions need to preserve state, or if they have a lot of shared data between them, then can be used coded as the Strategy Design Pattern.
Thanks for providing some context for Python/JS users. Yes all the examples shown are in C# and would probably be familiar for Java users but don't really work for non OOP languages.
I’ve found that some OO patterns don’t really make sense in Python because of functions being first-class citizens allowing you to pass functions around like a variable, where as other languages are weaker and need these patterns because you can’t simply pass a function. Same thing with Abstract Factory in Python.
Those languages are great because of flexibility. But if you want to enforce certain patterns, then it can be tricky.
For JavaScript, try typescript, for python, try abstract base class (abc) library.
OOP: we identified a set of things called patterns so that you could...
FP: JUST USE A FUNCTION FOR THAT (half-joking)
Now seriously, to me the top used C# patterns are:
- iterator (`foreach`)
- factory method (a factory interface injected via DI to make you a factory interface to make you a...)
- builder (hostBuilder.ConfigureLogging(...).ConfigureServices(...)....)
- strategy (which most of the 2nd-order functions implement)
- command (every closure is a command with Invoke method)
- interpreter (DSLs are nice)
I'm not mentioning singleton here because usually such scope is addressed by a DI-container
That cake and birthday party analogy was very good. Thanks for the video.
Thank you, I am glad! I wasn’t sure if it was a bit too abstract.
@@alexhyettdev just perfect. I love it too
Thanks Alex for such great content. It helped a lot to get a better understanding on what each of the 5 patterns is about. Keep it up!
You could say that the concept of a recipe is a design pattern. It's structured so that it has a list of ingredients, and the method for making the food.
much helpful, and a nice explanatory video to start with zero knowledge of design patterns.
Glad it was helpful!
Builder and Template Method are two other patterns I use occasionally.
7:26 how about locking before the null check? Why would you duplicate the code and add more nesting, when you can simply lock before the if...
If you do it that way, the lock will be performed every time GetInstance() is called. It will only be null once, so the way it's done in the video will require two locks at the most, probably just one.
That's what I thought too. Don't need to check twice if one thread is being locked out whilst the other is creating the object.
@@zo1dbergit's a kind of optimization. Taking a lock is a heavy operation, checking for null before it helps us avoid taking lock every time when we need an instance
@@valekseevGood point
So Strategy pattern is actually the same as programming in interfaces (or polymorphism)?
background is awesome. purple color. nice. how much it all costed.
What a neat explanation about the singleton pattern!" Thank you
Amazing way explaining these patterns.
God Damn It! Now I want all those cakes. Brings back memories of eating all of those in different parts of the world with friends and family
Two mnemonics to remember:
"Create Structures and Behave: Single Decorated Faces Observe Strategies"
Create Structures and Behave:
- Create reminds you of Creational patterns.
- Structures points to Structural patterns.
- Behave refers to Behavioral patterns.
Single Decorated Faces Observe Strategies:
- Single stands for Singleton (Creational).
- Decorated for Decorator (Structural).
- Faces for Facade (Structural).
- Observe for Observer (Behavioral).
- Strategies for Strategy (Behavioral).
I like something more fun, so here we go
"Crazy Squirrels Build Dens, Often Strategically"
- Crazy hints at Creational patterns.
- Squirrels Build Dens points to the Structural patterns.
- Often Strategically suggests Behavioral patterns.
Within each category:
- Single (from Squirrels) for Singleton (Creational).
- Build (Beginning of Build) for Decorator and Dens (D of Dens) for Facade (both Structural).
- Often for Observer and Strategically for Strategy (both Behavioral).
Thanks for the video. In .NET we have one extension method in service class to add single instance of the class(AddSingleton). Do we still need to use singleton design pattern?
It makes sense to learn the top 5 design patterns first, thanks.
Yes there are so many of them, got to start somewhere. I am sure there are a few I have never used as well.
While it's good to know about singletons, you genereally don't want to explicitly codify them. It's almost always best to let your DI container give you one.
Great video. Never heard about the Facade pattern, when you started explaining it I thought it was the Adapter pattern, What's the difference between them?
An adapter can be a function, or class, which acts as a translator between one functions/class output and another's input
Facade is more like a nice function, or class, that's easy to use and acts as the main interface/function which hides a lot of ugliness underneath to get things done
A facade of a house hides all the details on the inside, but you get a basic idea on what the house is used for by checking it's exterior - it's facade - see a police building for example
@@PixelThorn Thanks!
A facade doesn't have to be a nice abstraction on top of a mess. It could be you just want to abstract multiple types behind an interface so all types (usually of a third party) look the same, i.e. they have the same facade, to the consumer of them - otherwise the consumer would need to know each implementation. An adapater is about translating something into something else and acts like a middelware between the two things.
@@fifty-plus 💯 That’s when I’ve used a facade pattern in the past - when our application needed to send messages and make calls to outside services, and we knew we’d be swapping out those services over the next few months. All our internal classes called simple, standardized methods on the facade, and we just updated the internals of the facade to handle the various API implementations of the external services. Kind of an adapter as well? But the reason why we did it was to keep things clean and stable over time.
I really like your metaphor at the beginning!
Thank you! I am never 100% sure whether my metaphors are helpful
How about the Command Design Pattern. I use the pattern often
Finally someone without stupid PewDiePie-style jokes and with good material
I agree the bite-sized concept are well explained. I subscribed I hope to see more.
Lambda functions & closures became the big thing in the last 10 years & probably still are.
Fantastic video -- thank you! I plan to check out your other videos, perhaps find more design pattern goodness. Subscribing either way.
Hey... I'm a little confused about the decorator patern, what are the benefits over inheriting the class and overriding a virtual method?
The good thing about a decorator is that it can extend any class. So you write a functionality once and plug it in any class that you want, without duplicating code. You can also use it while extending a class you can't access I think, so you can extend a class while not being able to change anything inside it (the open-closed principle he refers to)
I can see these being used for the backend, But for something like React I find it a bit difficult to adapt these
I don't agree with how you described your Strategy pattern with the cakes (but I also don't think you displayed what "GetMethod()" was supposed to do).
The example with Google Maps illustrated it well: The context being the various modes of travel, returning the strategy (method) of how to perform the action.
To further elucidate, other modifiers to this context could be [additional stops, fastest route, avoid traffic, no tolls, no freeways, etc] which then returns a different, modified strategy (method) of how to get from A->B.
thanks for this most noble sire
Amazing content bro 😎
Thank you ! amazing video
I'm sorry I still did not get it - the prerequisite for the decorator pattern is that one is obliged to use another implementation of the same interface - you just may expand it by putting your extra staff here and there?
Yes, that's exactly how you use the pattern. An example would be a logger. The logger has a certain basic functionality that is the same throughout the entire project. In this example, however, you want to save/output the time and the component in which the message was logged for step A. In step B, the time should not be displayed in the log messages. Instead, the type of the log message (warning, error, info ...) should be displayed there.
This behaviour can of course be implemented in many different ways. For example, you could add a timestamp attribute to a log message and specify a flag as to whether the date object should also be displayed. This approach works, of course. And in smaller projects, there is definitely no reason not to use such an approach. However, the more such requirements are added, the more complex the code of the class becomes. This means it is more difficult to extend / maintain / understand the code. With the decorator pattern, the logic required for the individual use cases can only be found in the special decorator. This keeps the basic functionality of the logger tidier and therefore easier to maintain.
However, if more similar use cases are added, the Decorator pattern is of course an obstacle. Assuming you simply want to be able to switch the individual extras (time, type, location) on and off and you need each of the 2^3 cases in your project, this would mean that you would have to write 8 Decorators with similar functionality.
"Not actually my wife" got me good 🤣
🤣
Hi, random question out of curiosity. Actually instead of implementing singleton in this way isn't it more common to register as a singleton service via Dependency Injection ? I think I have never encountered it yet being designed like this and maybe it's just me being exposed to the same style on the projects i work on.
In your singleton pattern, why wouldn't you just lock once and check whether the instance is null inside the mutex locked code block? What is the purpose of the instance == null check outside the lock?
@cern1999sb This is called the Double-null check pattern. It eliminates the overhead of acquiring the lock on every method invocation when it's only really needed once.
So useful!
Glad it was helpful!
Hi. What is the purpose of the default setter in the Value property of LazySingleton? {time => 7:43}
Great video. As a Java developer I not only use the patterns you mentiond but also Visitor, Factory, Builder and Composite. I think they are very common too.
My opinion: These contrived analogies, such as using cake really don't work when trying to explain something in software. You are explaining to technical developers, not children. In my experience these long winded analogies only distract me from what you are talking about, especially when showing B-roll of cutting very attractive looking cake. Really, only 40% of my attention is on what you are actually trying to say and most is focused on the sweetness, softness and taste of the cake, all of which are very strong distractors.
So you are easily distracted?
Great explanation. Thank you
Glad you liked it
I have reservations against the singleton pattern. Functional style programming combined with immutability kind of makes it unnecessary. If your code doesn't actually care about the object's reference, only it's value, and that value can never change, the optimizations that result is effectively your singleton, and you didn't even have to write it.
Great video! Thanks
very nice ! thanks for sharing
Singleton is the worst design pattern I have used. You do want to be able to create multiple DB connections, unit tests and all…
Yes. It's called an anit-pattern for good reason.
bringing alcohol to the party is a design pattern
Great explanations thank you for your effort. Which color theme do you ise in Vs Code?
Thank you! It is the Atom One Dark theme:
marketplace.visualstudio.com/items?itemName=akamud.vscode-theme-onedark
Man you deserve 1m subscribers ❤❤ can you make a node js DDD hexagonal archeticture CQRS Event sourcing course
Thank you! Yes I might be able to do a course on that in the future.
I prefer to remember decorator patern as ecorato pattern
Wow - Thanks for the great content.
You're welcome! Thanks for commenting
Builder? Used ALL over the .NET Core. Chain of Responsibility - same, plus all the different "Fluent"Something. Factory method - all of the IoC/DI are factories on steroids, Iterator - every collection in .NET...
No dependency injection pattern??
Thank you for a great introduction to Design Patterns.
{2024-07-09} - Subscribed!
Desde o vanilla JS eu já evito usar Node, sempre tento forçar Element. Por exemplo, ao invés de pegar o último filho de um elemento com element.lastChild (que inclui todos os Nodes), uso element.lastElementChild (que inclui somente HTMLElements), pois Node pode ser até mesmo os espaços em branco soltos no HTML (por mais que não apareça na tela).
Some people argue that design patterns can lead to over-engineering. Do you agree?
What about MVC
How does Decorator differ from Facade tho...
isnt CQRS used widely as well?
I use it in my current job, even though they just introduced it, but in my 25+ years of programming this is the first time I've ran across it.
Man you should put on a cake warning. Now I want some cake.
The cake is a lie
Are they 23 ?
I count only 22.
Am I missing something ?
I don't get the first one, the Strategy Pattern. Isn't it just an Interface?
Your objects would be arguments into a constructor
public interface IOption {...}
class OptionOne : IOption { // some implemention}
class OptionTwo : IOption { // some implemention}
class MyTool
{
private readonly _theAction;
public MyTool(IOption theAction)
{
this._theAction = theAction
}
}
Now you can create a tool and assign actions without needing to recompile
MyTool toolOne = new MyTool(new OptionOne());
Of course you might add additional things, actions. Like which file formats, checks, reads, etc. Into the tool.
With modern dependency injection a Singleton pattern is very outdated. I personally haven't used it for over 5 years. Moreover, controlling an object lifetime by the object itself seems to conflict with a single responsible principle and would definitely mark a Singleton code down in a code review.
I have only ever heard about singleton patterns discussed in theory. I have never seen that pattern actually be implemented in the wild. Closest thing is managing dependencies and calling addsingleton, addscoped, or addtransient.
I think programmers need to get real about just saying things to look smart.
Uniswap V4 uses singleton pattern.
Bare Minimum these 6 pattern
Singleton
Factory
Decorator
Facade
Observer
Strategy
It is not easy to memorize all design patterns, nor their benefits
dude is that a 'back to the future' time panel? insta like and subscribe :)
It is! I wish it was more than just a light. I might have to make a working one at some point.
It here if you wanted on yourself: numskull.com/products/official-back-to-the-future-3d-desk-lamp-wall-light
Singleton is an antipattern. It's a violation of SRP and makes unit testing unnecessarily difficult. If you need a singleton object, you should enforce that elsewhere in the code or use dependency injection.
Like many videos and books on design patterns, this videos also fails to meet the most desired objective - to help developers choose the right design pattern when certain situations are presented to them. The fancy names of the patterns and their explanation is great, but if developers are not able to analyze a problem and quickly "map" it to one of these patterns, then it isn't really useful.
The notion of so-called "design patterns" was inherent in even the most early functional languages, e,g. lisp, but they were called "expressions" whose function definitions might or might not contain other expressions! It's not rokit syance, and DEFINATELY not LATTER-DAY object-oriented pseudo-paradigm-ical mumbo-jumbo! Simples, as simple can be! (:-)
It’s interfaces all the way down 😂
"Not actually my wife" 😂
For some strange reason I want cake now.
It's always time for cake!
Nice
I'm surprised I know the def of all also how to implement them 😅
Yes, plus Factory. The rest are VERY RARE!
You didn't explain the strategy pattern. What you explained sounds like the visitor pattern
design patterns are way overrated, you don't need to know them well to become a good engineer
Software engineer are not made on websites, you're more a developer, someone learning something very specific, taking a biology course doesn't make you a doctor, what a woke joke
What is ryan reynolds doing on this video ?
I am flattered and should look into getting a Deadpool outfit for my next video 😂
@@alexhyettdevyes, the multiverse needs you man 👊
You shouldn't use the observer pattern. You should use the event pattern with an event handler class instead. The observer pattern polls and breaks encapsulation. Event patterns act as an interrupt, thus using less process time and only needs to know that the event handler exists and that there is an object that creates an event that you subscribe to through the event handler.
edit: The pattern you've described in the video is the event pattern, and not the observer pattern. Please use the appropriate name.
This video shows a textbook example of the observer pattern. The observer pattern is when a subject maintains a list of its observers and automatically notifies the observers when the subject changes (no polling involved).
Using the names Publisher/Subscriber may cause confusion for people familiar with the pub-sub pattern though.
As far as I can tell, there's no common pattern called the "event pattern". What are you trying to refer to?
From my understanding the entire point of the observer pattern (right from the Gang of Four) is to avoid polling. I’m wondering if you may have learned the wrong name for the observer pattern?
@@TeenyPort The implementation of the observer pattern I saw was the original small talk implementation from somewhere between the late 70's to the early 90's pre Design Patterns being written, there was a newer version that didn't poll, and then an event pattern that was also available. It made for some rough to follow coding standards.
Why I recommend the event pattern is because the observer pattern does break encapsulation by knowing the object being observed has a state you are interested in.
The event pattern only requires you to know the object exists, has an event, and there is an event handler object. The object of interest registers with the event handler that it exists and that it has the events it has. The object interested in the events registers its interest in those events from the object. Every object has an event queue. When the object of the events of interest triggers the event it publishes it to the event handler that then distributes it to the subscribed objects. This allows for better debugging process, lowers the risk of operations performing out of order, and removes a variable on all objects of the interested in queue while also allowing multiple actions to be observed improving overall performance.
The observer pattern was almost not included in design patterns because of its issues with breaking encapsulation and runtime debugging. I'd say within 5 years of design patterns being published someone invented the event pattern because of all of its superior performance capabilities. The reason it isn't the standard is that every years there are twice as many new programmers entering the job market than the year before so there isn't enough time to develop new programmers and pass on institutional knowledge. Since Design Patterns is the gold standard of how to make a program, even if it is now 30 years old.
According to whom I need to know, NASA?
Well, if you have DesignPatterns in vid tittle, do you have to keep repeating it every 5 sec?? We got this, rlly - vid is about D-Patterns... Ok chill...
skip to 2:45 to skip the preamble and get to the point.
That’s why I include time stamps in all my videos. Not everyone knows what design patterns are or wants to listen to my analogies 🤣
You use what - Singleton?! Ugh. Nevermind. Ask Allen Holub instead. 😂😂😂
It is always astounding how people who (probably) believe they are professional developers get all excited about trivial videos like these. Nothing wrong with the video, but ... really?
Really what?
Ah yes I too am very smart and professional because I know all my patterns.. clearly I was born this way and never had to learn anything like those puny unprofessionals...?
I went to your channel. Great content. I can see why you feel compelled to make snide comments about others.
Really, you are welcome to go bask in the magnificent glory your ennui.
Well explained. Thank you
Great Explanation. Thanks.