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.

Challenge: The Factory Method pattern

Challenge: The Factory Method pattern

In this challenge, you'll get to implement the factory method pattern in an app which represents a vending machine that dispenses various snacks. So let's have a look at the code you'll be working with. First of all, there's an interface called Snack, which has a method called getPrice. Then there are three classes which implement this interface. So one of them is Chips, the other one is ChocolateBar, and the third one is Drink. So these three classes all implement Snack and they override the getPrice method and return different values. Then there's the VendingMachine class. This class has a method called getSnack, which takes in arguments of type string, which is the snackType. And at the moment, this just returns null. But for this challenge, you'll need to implement the logic in this method so that it returns the right type of snack depending on what's passed in. So this method is going to be the factory method. And this VendingMachine class is the place where you'll be working on…

Contents