<< Chapter < Page Chapter >> Page >
Many real-life systems change the way they behave as they change states. It is desirable for object models of such systems to be able to change their behaviors as if they are changing types dynamically. The state design pattern is a design solution for this problem of dynamic reclassification. The key element is to abstract the state dependent behavior of the system in question as an abstract class and encapsulate each concrete variant behavior as a concrete subclass.

When modeling real-life systems, we often find that certain objects in our system seem to change "state" during the course of a computation.

Examples of changing state:

  1. A kitten grows up into a cat
  2. A car runs into a telephone pole and becomes a wreck.
  3. A friend is sad one day, happy another, and grumpy on yet another day.
  4. A list changes from empty to non-empty when an element is added.
  5. A fractal becomes more complex when it grows
  6. etc. etc.

The cat and the kitten are the same animal, but they don't act identically. A car can be driven but a wreck cannot--yet they are the same entity fundamentally. Your friend is the same human being, no matter what their mood. Why shouldn't a list be the same list and a fractal be the same fractal?

When something changes state, it is the same object, but yet it behaves differently . This phenomenon of having an objects change its behavior as if it were suddenly belonging to a whole different class of objects is called " dynamic reclassification ".

So far we've been using immutable data, and to create a non-empty list from an empty one, required that we make a whole brand-new list. With our use assignment ("=") previously, we've changed the value of a variable, but never the behavior the object it references.

Consider this notion: We want to change the type of the object but we want to encapsulate that change so that the outside world does not see the type change, only the behavior change.

Let's work with an example:

Remember the old arcade game, "Frogger"? That's the one where a traffic-challenged amphibian attempts to hop across multiple lanes of speeding cars and trucks, hopefully without being converted into the road-kill-du-jour.

(Here's an on-line version: (External Link) )

Well, let's look at what a frog is here:

A live frog

  • Has a well-defined position
  • Has a green color
  • Can move from place to place
  • Dies when hit by a vehicle.

On the other hand, a dead frog

  • Has a well-defined position
  • Has a decided red color.
  • Cannot move from place to place
  • Doesn't die when hit by a vehicle because it is already dead.

Using our trusty separation of variant and invariant, we can see that the position of a frog is an invariant but all the other behaviors are variants. Thus we want to separate out these variants into their own subclasses of an invariant abstract class. We then use composition to model the frog having an abstract state, which could be either alive or dead:

Download the code here.

Click here to download the full javadoc documentation of the above code.

The variant behaviors are represented by the abstract AFrogState , with the DeadState and LiveState implementing its abstract behaviors.

(Note: The IFrog interface is there simply to allow different formulations of the frog to exist. See the Question below.)

For those variant behaviors, all the main Frog does is to delegate (pass the call on to and return the result of) to the _state that it has. If the _state is a LiveState , then the Frog will act as if were alive because the LiveState only contains live-like behaviors. On the other hand, if the state is a DeadState , then the delegation to the _state will produce dead-like behavior. The LiveState 's getHit behavior will cause the Frog 's _state to change from referencing a LiveState instance to referencing a DeadState instance.

No conditionals are needed!!

The Frog behaves the way it does because of what it is at that moment, not because of what it can figure out about itself then.

This is an example of the State Design Pattern. Click here for more information on the State design pattern.

From the outside, nothing about the internal implementation of Frog can be seen. All one can see is its public behavior. The implementations of the state design pattern are completely encapsulated (within the frog package, in this formulation).. For instance, if one is moving a live Frog , it will dutifully move as directed, but if in the middle somewhere, the Frog is hit, then it will immediately stop moving, no matter how much it is asked to do so. If one is checking its color, the live Frog is a healthy green but right after its accident, it will report that it is deathly red.

Notice how the Frog changes its behavior and always behaves correctly for its situation, with no conditional statements whatsoever .

Question:

A very nice technique, when it is possible, is to implement the State pattern using anonymous inner classes. Can you write an IFrog implementation that encapsulates the states using nested class(es)and anonymous inner class(es)?

  • It can be done using only one publicly visible class and no package visible classes at all.
  • The only methods needed are those specified by IFrog .
  • How does using anonymous inner class(es) reduce the number of parameters passed to the state?
  • How does using the anonymous inner class(es) reduce the number of non-public methods?

Onward!

Looking way back to the beginning of the semester, we now have to ask, "Can we use this technology to create a mutable list? How will this affect the visitors and their execute function?" Hmmmm.....

Questions & Answers

what is phylogeny
Odigie Reply
evolutionary history and relationship of an organism or group of organisms
AI-Robot
ok
Deng
what is biology
Hajah Reply
the study of living organisms and their interactions with one another and their environments
AI-Robot
cell is the smallest unit of the humanity biologically
Abraham
what is biology
Victoria Reply
what is biology
Abraham
HOW CAN MAN ORGAN FUNCTION
Alfred Reply
the diagram of the digestive system
Assiatu Reply
allimentary cannel
Ogenrwot
How does twins formed
William Reply
They formed in two ways first when one sperm and one egg are splited by mitosis or two sperm and two eggs join together
Oluwatobi
what is genetics
Josephine Reply
Genetics is the study of heredity
Misack
how does twins formed?
Misack
What is manual
Hassan Reply
discuss biological phenomenon and provide pieces of evidence to show that it was responsible for the formation of eukaryotic organelles
Joseph Reply
what is biology
Yousuf Reply
the study of living organisms and their interactions with one another and their environment.
Wine
discuss the biological phenomenon and provide pieces of evidence to show that it was responsible for the formation of eukaryotic organelles in an essay form
Joseph Reply
what is the blood cells
Shaker Reply
list any five characteristics of the blood cells
Shaker
lack electricity and its more savely than electronic microscope because its naturally by using of light
Abdullahi Reply
advantage of electronic microscope is easily and clearly while disadvantage is dangerous because its electronic. advantage of light microscope is savely and naturally by sun while disadvantage is not easily,means its not sharp and not clear
Abdullahi
cell theory state that every organisms composed of one or more cell,cell is the basic unit of life
Abdullahi
is like gone fail us
DENG
cells is the basic structure and functions of all living things
Ramadan
What is classification
ISCONT Reply
is organisms that are similar into groups called tara
Yamosa
in what situation (s) would be the use of a scanning electron microscope be ideal and why?
Kenna Reply
A scanning electron microscope (SEM) is ideal for situations requiring high-resolution imaging of surfaces. It is commonly used in materials science, biology, and geology to examine the topography and composition of samples at a nanoscale level. SEM is particularly useful for studying fine details,
Hilary
Biology is a branch of Natural science which deals/About living Organism.
Ahmedin Reply
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Principles of object-oriented programming. OpenStax CNX. May 10, 2013 Download for free at http://legacy.cnx.org/content/col10213/1.37
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?

Ask