<< Chapter < Page
  Design patterns   Page 1 / 1
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 does preconceived mean
sammie Reply
physiological Psychology
Nwosu Reply
How can I develope my cognitive domain
Amanyire Reply
why is communication effective
Dakolo Reply
Communication is effective because it allows individuals to share ideas, thoughts, and information with others.
effective communication can lead to improved outcomes in various settings, including personal relationships, business environments, and educational settings. By communicating effectively, individuals can negotiate effectively, solve problems collaboratively, and work towards common goals.
it starts up serve and return practice/assessments.it helps find voice talking therapy also assessments through relaxed conversation.
miss
Every time someone flushes a toilet in the apartment building, the person begins to jumb back automatically after hearing the flush, before the water temperature changes. Identify the types of learning, if it is classical conditioning identify the NS, UCS, CS and CR. If it is operant conditioning, identify the type of consequence positive reinforcement, negative reinforcement or punishment
Wekolamo Reply
please i need answer
Wekolamo
because it helps many people around the world to understand how to interact with other people and understand them well, for example at work (job).
Manix Reply
Agreed 👍 There are many parts of our brains and behaviors, we really need to get to know. Blessings for everyone and happy Sunday!
ARC
A child is a member of community not society elucidate ?
JESSY Reply
Isn't practices worldwide, be it psychology, be it science. isn't much just a false belief of control over something the mind cannot truly comprehend?
Simon Reply
compare and contrast skinner's perspective on personality development on freud
namakula Reply
Skinner skipped the whole unconscious phenomenon and rather emphasized on classical conditioning
war
explain how nature and nurture affect the development and later the productivity of an individual.
Amesalu Reply
nature is an hereditary factor while nurture is an environmental factor which constitute an individual personality. so if an individual's parent has a deviant behavior and was also brought up in an deviant environment, observation of the behavior and the inborn trait we make the individual deviant.
Samuel
I am taking this course because I am hoping that I could somehow learn more about my chosen field of interest and due to the fact that being a PsyD really ignites my passion as an individual the more I hope to learn about developing and literally explore the complexity of my critical thinking skills
Zyryn Reply
good👍
Jonathan
and having a good philosophy of the world is like a sandwich and a peanut butter 👍
Jonathan
generally amnesi how long yrs memory loss
Kelu Reply
interpersonal relationships
Abdulfatai Reply
What would be the best educational aid(s) for gifted kids/savants?
Heidi Reply
treat them normal, if they want help then give them. that will make everyone happy
Saurabh
What are the treatment for autism?
Magret Reply
hello. autism is a umbrella term. autistic kids have different disorder overlapping. for example. a kid may show symptoms of ADHD and also learning disabilities. before treatment please make sure the kid doesn't have physical disabilities like hearing..vision..speech problem. sometimes these
Jharna
continue.. sometimes due to these physical problems..the diagnosis may be misdiagnosed. treatment for autism. well it depends on the severity. since autistic kids have problems in communicating and adopting to the environment.. it's best to expose the child in situations where the child
Jharna
child interact with other kids under doc supervision. play therapy. speech therapy. Engaging in different activities that activate most parts of the brain.. like drawing..painting. matching color board game. string and beads game. the more you interact with the child the more effective
Jharna
results you'll get.. please consult a therapist to know what suits best on your child. and last as a parent. I know sometimes it's overwhelming to guide a special kid. but trust the process and be strong and patient as a parent.
Jharna
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, Design patterns. OpenStax CNX. Jun 04, 2009 Download for free at http://cnx.org/content/col10678/1.2
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Design patterns' conversation and receive update notifications?

Ask