Reputation: 323
I am studying design patterns, and at one moment caught myself with an idea, that most creational patterns like Factory and Abstract Factory are not so useful in the scope of a dependency injection environment where we usually don't create objects with the new
keyword but "inject" them from some context. I also understand that most probably I am wrong and I need a good explanation to make things clear.
Upvotes: 6
Views: 1267
Reputation: 6255
DI frameworks like Spring initialize and manage beans. Creational pattern can be used to create domain (bussines) objects.
Upvotes: 0
Reputation: 17066
You are not wrong. There are five creational patterns in the GoF book and you will likely never use any of them as a Java developer.
Upvotes: 5
Reputation: 6117
Using a Dependency Injection / Inversion of Control framework such as Spring does indeed reduce the need for The Gang of Four Creational Patterns, but may not eliminate them.
First, let's notice that Spring supports a scope ( instance creation mode ) called "Singleton". And while its implementation varies from the GOF suggested one, many of the ideas are the same. In this case, if Spring is prevalent throughout your project, you would not need the GOF singleton. As noted elsewhere, developers should be wary of Singleton abuse, as Singletons can lead to static, untestable and unconfigurable code.
Next, the Abstract Factory is used to create entire families of related products. The 1 product simplified type was not even mentioned in the GOF book. I suppose they considered it to be too well known already. In a Spring environment you will often use Spring to inject the product you need instead of creating it through a factory, but in some instances, you will inject the factory instead, and then create products from it!
Prototype is another confusing one. The GOF patterns is rarely used in languages with reflection as they really do have other ways, although not necessarily better ways for creating a copy of an object. The confusing bit is that Spring uses the word "Prototype" to denote a Bean which is not a singleton, I guess because they originally assumed that all new instances of this Bean would essentially start out the same.
Factory Method is usually used by in Frameworks, and less so in Application level code. It lets the user of the Framework decide what kind of object is created when the framework chooses to create an object. Spring actually does something very similar but without inheritance. When you mark a function as @Bean, Spring calls your function when it wants to create a new instance, replacing Factory Method's inheritance mechanism with Spring's reflection and interception.
Upvotes: 2