Instruction 2

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.

Contact Contact Contact Contact Factory createPersonContact() createCompanyContact() createCompanyContact() createPersonContact()
Contacts Factory Diagram

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
Download course materials from Github
Previous: Demo 1 Next: Demo 2