As a junior developper, i’m a bit confused about some design patterns. Sometimes, i just don’t know which to use in which context.
For exemple, on creational patterns, i don’t really know when to use:
- Factory
- Prototype
- Builder
Actually, i see some differences; but i also see that you can use multiple solutions like:
- Calling a factory that calls the appropriate builder that clones a prototype.
- Calling a factory that clones the appropriate prototype
- Calling a builder with the appropriate director
- …
I mean, the result of these creations is at the end the same: you get your object instance.
I just wonder what kind of design you would use on different contexts (i guess it could be depending on performence needs, objects complexity, coupling…)
Also, I don’t really see a big differences between a facade and a mediator, except the mediator calls different interfaces.
Same for chain of responsability, don’t really understand why all implementations i see use chained lists. Can’t this pattern be implemented with a simple List of handlers that we call successively?
That’s why i’d like people to tell me in which concrete context you would use a GoF pattern, and also why you wouldn’t use any of the other patterns that could have fit to the given problem (but probably in a less elegant way).
Thanks
Like many people when I first came across design patterns I realized that a lot of them were simply names for mechanisms I’d already used to solve design problems. The problem came first, then the solution. I never approached design patterns like they were puzzle pieces that needed to fit somewhere.
You’re not really required to answer a problem with the name of a pattern as if it was an exam. The way to do it is to sit down and think about what you need your code to do and how it may change in the future. This is how we got to these design patterns anyway. People kept using the same tricks to solve a certain set of problems until eventually someone came along and gave those tricks names.
The only problem you have is lack of experience and that can’t be fixed just by SO. As you write software you’ll invariably get some things wrong. You’ll discover that if you had done things this way, they would have been better. Incidentally this way has a name; “abstract factory”, “adapter”, “observer”, whatever. In the future you’ll know when and why to use it. For now remember the KISS principle. Don’t complicate things that don’t have to be complicated.
The fact that you’re aware of design patterns before knowing how to use them means that you’re a step ahead of most devs. Don’t sweat it too much, just remember that next time you have a problem one of them might be an acceptable answer. Little by little you’ll find out when a design pattern should be used and when it shouldn’t.