From the course: Complete Guide to Java Design Patterns: Creational, Behavioral, and Structural

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Understand the Factory Method pattern

Understand the Factory Method pattern

The factory method is a pattern that handles deciding which type of concrete class needs to be created by another class. This is best explains with an example. So imagine there's an application called a ticket machine, which creates tickets for public transport. Initially, the ticket machine might only create bus tickets, so that's fairly straightforward to implement. I would have a TicketMachine class and a Ticket class, and the TicketMachine class creates Ticket objects. So far so good. But later, I might want to have ticket machines that sell different types of tickets, for example, train tickets. So in my code, I might introduce a ticket interface with two concrete implementations called bus ticket and train tickets. The problem is that the TicketMachine class doesn't know in advance which type of ticket it needs to create; bus tickets or train tickets. This is the problem that the factory method pattern solves. There are a couple of different variations of this pattern. One…

Contents