In the previous demo, you implemented the Singleton pattern on ContactsBook. This prevents anyone from creating multiple instances of the contact book and ending up without a real source of truth for the list of contacts in the program.
Now, you’ll move on to solving a different problem that’s related to the method you’re using to instantiate contacts. When you first started building the program, you had one class: ContactCard. But as your program expanded, you created two new types: Person and Company. This allowed you to hide some implementation details behind those types and their constructors.
The result was that the rest of the system became aware of two new types, even though it doesn’t care about them, and they don’t offer anything to the rest of the system. It’s all a data modeling issue.
Fortunately, the Factory pattern is here to save the day. With a real factory, you don’t know many manufacturing details about a product; that “construction” information is abstracted away from the consumer. The Factory pattern does the same for your program.
When you have many different types that all share a base type, the factory can take care of the construction differences and return all of them as instances of the base type. This makes the system completely unaware of the multiple child types you might have.
By utilizing dedicated methods to create the various contact types your system needs and delivering them all under the umbrella of the base class, ContactCard, your system accesses all necessary functions without any knowledge of the derived classes. You can add as many contact types as you need in the future, and that knowledge is “classified” so only the factory can access it.
The Factory pattern doesn’t just hide child types — it hides the construction process as a whole. If creating and setting up each object requires multiple method calls and several operations, the factory will hide all that.
See forum comments
This content was released on Oct 17 2023. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.