From the course: Java Design Patterns: Creational

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Implement a simple Factory Method pattern

Implement a simple Factory Method pattern - Java Tutorial

From the course: Java Design Patterns: Creational

Start my 1-month free trial

Implement a simple Factory Method pattern

- [Instructor] In this example, there is an application that would benefit from being refactored to use a factory method. In the application, there is a candy store that sells two different types of candy, chocolates and hard candy. It has an abstract class called Candy, which declares a single abstract method called makeCandyPackage. This method takes a number as an argument. It returns a list of candy with that number of candy in it. It then has two classes that extends the candy class. These are Chocolates and HardCandy. Both overrides the abstract makeCandyPackage method. In the Chocolate class, it creates a list and adds new chocolates to it. For example, if the number 7 is passed into the method, it creates seven new chocolates and adds them to a list. It then returns that list of chocolates. The hardCandy class does the same. It creates and returns a list of hard candy rather than a list of chocolates. The CandyStore class needs to get packages of candy. Because the candy store…

Contents