From the course: Java Design Patterns: Behavioral Part 2

Unlock the full course today

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

Avoiding large switch statements

Avoiding large switch statements - Java Tutorial

From the course: Java Design Patterns: Behavioral Part 2

Start my 1-month free trial

Avoiding large switch statements

- [Instructor] In this example, I have a media player application that I'm going to refactor to use the state pattern to simplify it. So let's have a look at the code. First of all, I have a main class with a main method. In here I'm creating a media player object. Then I'm calling its play method and its pause method. So if I run the app, I can see this it prints out two messages to the console. The first thing that the video is playing, and the icon is set to a pause button and the second says that the video is paused and the icon is set to a play button. So now let's have a look at this media player class. This has two fields, both of types string, called states and icon. In a real application, the icon would be an actual image but to keep this example simple I'm just using a string to describe where the icon would be. So to start with the state is set to paused and the icon is set to a play button. Then I have a…

Contents