Redesign the Gumball Machine Define a State interface that contains a method

Redesign the gumball machine define a state interface

This preview shows page 18 - 27 out of 29 pages.

Redesign the Gumball Machine Define a State interface that contains a method for every action in the Gumball Machine Implement a State class for every state of the machine. These classes will be responsible for the behavior of the machine when it is in the corresponding state Get rid of all the conditional code and delegate the work to the state class
Image of page 18
The New Design
Image of page 19
Image of page 20
Image of page 21
Image of page 22
Image of page 23
When to use STATE pattern ? State pattern is useful when there is an object that can be in one of several states, with different behavior in each state. To simplify operations that have large conditional statements that depend on the object’s state. if (myself = happy) then { eatIceCream(); …. } else if (myself = sad) then { goToPub(); …. } else if (myself = ecstatic) then { ….
Image of page 24
Example I water StateOfWater WaterVapor LiquidWater Ice increaseTemp() decreaseTemp() state variable Client increaseTemp() increaseTemp() decreaseTemp() increaseTemp() decreaseTemp() increaseTemp() decreaseTemp() increaseTemp() decreaseTemp()
Image of page 25
How is STATE pattern implemented ? “Context” class: Represents the interface to the outside world. “State” abstract class: Base class which defines the different states of the “state machine”. “Derived” classes from the State class: Defines the true nature of the state that the state machine can be in.
Image of page 26
Image of page 27

You've reached the end of your free preview.

Want to read all 29 pages?

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes