<< 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

A golfer on a fairway is 70 m away from the green, which sits below the level of the fairway by 20 m. If the golfer hits the ball at an angle of 40° with an initial speed of 20 m/s, how close to the green does she come?
Aislinn Reply
cm
tijani
what is titration
John Reply
what is physics
Siyaka Reply
A mouse of mass 200 g falls 100 m down a vertical mine shaft and lands at the bottom with a speed of 8.0 m/s. During its fall, how much work is done on the mouse by air resistance
Jude Reply
Can you compute that for me. Ty
Jude
what is the dimension formula of energy?
David Reply
what is viscosity?
David
what is inorganic
emma Reply
what is chemistry
Youesf Reply
what is inorganic
emma
Chemistry is a branch of science that deals with the study of matter,it composition,it structure and the changes it undergoes
Adjei
please, I'm a physics student and I need help in physics
Adjanou
chemistry could also be understood like the sexual attraction/repulsion of the male and female elements. the reaction varies depending on the energy differences of each given gender. + masculine -female.
Pedro
A ball is thrown straight up.it passes a 2.0m high window 7.50 m off the ground on it path up and takes 1.30 s to go past the window.what was the ball initial velocity
Krampah Reply
2. A sled plus passenger with total mass 50 kg is pulled 20 m across the snow (0.20) at constant velocity by a force directed 25° above the horizontal. Calculate (a) the work of the applied force, (b) the work of friction, and (c) the total work.
Sahid Reply
you have been hired as an espert witness in a court case involving an automobile accident. the accident involved car A of mass 1500kg which crashed into stationary car B of mass 1100kg. the driver of car A applied his brakes 15 m before he skidded and crashed into car B. after the collision, car A s
Samuel Reply
can someone explain to me, an ignorant high school student, why the trend of the graph doesn't follow the fact that the higher frequency a sound wave is, the more power it is, hence, making me think the phons output would follow this general trend?
Joseph Reply
Nevermind i just realied that the graph is the phons output for a person with normal hearing and not just the phons output of the sound waves power, I should read the entire thing next time
Joseph
Follow up question, does anyone know where I can find a graph that accuretly depicts the actual relative "power" output of sound over its frequency instead of just humans hearing
Joseph
"Generation of electrical energy from sound energy | IEEE Conference Publication | IEEE Xplore" ***ieeexplore.ieee.org/document/7150687?reload=true
Ryan
what's motion
Maurice Reply
what are the types of wave
Maurice
answer
Magreth
progressive wave
Magreth
hello friend how are you
Muhammad Reply
fine, how about you?
Mohammed
hi
Mujahid
A string is 3.00 m long with a mass of 5.00 g. The string is held taut with a tension of 500.00 N applied to the string. A pulse is sent down the string. How long does it take the pulse to travel the 3.00 m of the string?
yasuo Reply
Who can show me the full solution in this problem?
Reofrir 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