I just learnt my third design from the Head First Design Pattern book. Today, I learnt about the Abstract Factory method and Factory Method.
According to Head First Design Patterns, the Factory Method pattern is a pattern that allows you to defer the instantiation of an object to a subclass. It does so by defining an interface and letting its subclasses design which class to instantiate.
The Abstract Factory is a design pattern that provides an interface for creating a family of related objects without specifying their concrete classes.
These two design patterns help you decouple your code from concrete classes. Thereby promoting loose coupling between your classes. The Factory method relies on inheritance to achieve this loose coupling. It delegates the logic of creating concrete classes to its subclasses while the Abstract Factory pattern relies on object composition.
Whenever you have a family of related objects to create, you should use the Abstract Factory Pattern else use the Factory Method pattern.
Top comments (6)
Is this something still useful in Kotlin for your work with Android?
The factory pattern is a very basic pattern used in many places, including Android development, also with Kotlin. In fact, many types in Android frameworks are instantiated with factory methods, and you may actually have written factory methods or classes already yourself without knowing it.
Yea I know I have used it in other languages and frameworks. It is referred to in Effective Java as well. The specifics of Android are new to me. I am currently taking the Google course on it with hopes of gaining the certification at the end of the year! Also developing an app on the side using Jetpack Compose concepts with hopes to do a KMP back end and eventual SwiftUI front end for an iOS version. Thanks again for your tips! Shot you a follow to see the other interesting tid bits you post!
Wow ,that's very very cool. Good luck with the certification exams! What do you think about Compose?
So far I like it much better than using XML and the Views concept of old.
I've never used this before. I think it would be very for e commerce type apps with different kinds of objects. As i'm just learnt this design pattern, maybe i'll run into usecases where i can use it! ;D