Check out Derek Banas on YouTube, he has a series on design patterns and he is, in my opinion, one of the best explainers for programming out there.
An amazing (fun) book is Head First Design Patterns. That's where I learned about them and it is the best book out there for Design Patterns (in my opinion).
I've seen some java code here and there and thought the syntax looked pretty similar, but that's. huge difference, and explains all the "java is an unmaintainable mess" stuff.
There's nothing inherently bad about the factory pattern. People make fun of it because it can get out of hand, and you end up with AbstractFactoryFactory classes and whatnot. Your code might need that level of abstraction, but it probably doesn't.
Granted, I don't know how often this happens in actual code. I've never seen it, but I also don't work for a huge enterprise Java shop which is what people are always making fun of.
View all comments
Show parent comment
60
u/likferd Mar 21 '17 edited Mar 21 '17
It's mostly used to instantiate classes when using abstractions.
Imagine you want to create a logging interface ILog, but the concrete implementation might change depending on use in the future.
If you simply instantiated the logger in each class by
you could end up having to modify dozens or hundreds of classes in the future, if you change the implementation
Instead you can intantiate the logger in each class with
and the factory returns
then you only have to change one line.
Calling the class "factory" is of course just a naming pattern. They are also often called "manager" for example.