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

differentiate between demand and supply giving examples
Lambiv Reply
differentiated between demand and supply using examples
Lambiv
what is labour ?
Lambiv
how will I do?
Venny Reply
how is the graph works?I don't fully understand
Rezat Reply
information
Eliyee
devaluation
Eliyee
t
WARKISA
hi guys good evening to all
Lambiv
multiple choice question
Aster Reply
appreciation
Eliyee
explain perfect market
Lindiwe Reply
In economics, a perfect market refers to a theoretical construct where all participants have perfect information, goods are homogenous, there are no barriers to entry or exit, and prices are determined solely by supply and demand. It's an idealized model used for analysis,
Ezea
What is ceteris paribus?
Shukri Reply
other things being equal
AI-Robot
When MP₁ becomes negative, TP start to decline. Extuples Suppose that the short-run production function of certain cut-flower firm is given by: Q=4KL-0.6K2 - 0.112 • Where is quantity of cut flower produced, I is labour input and K is fixed capital input (K-5). Determine the average product of lab
Kelo
Extuples Suppose that the short-run production function of certain cut-flower firm is given by: Q=4KL-0.6K2 - 0.112 • Where is quantity of cut flower produced, I is labour input and K is fixed capital input (K-5). Determine the average product of labour (APL) and marginal product of labour (MPL)
Kelo
yes,thank you
Shukri
Can I ask you other question?
Shukri
what is monopoly mean?
Habtamu Reply
What is different between quantity demand and demand?
Shukri Reply
Quantity demanded refers to the specific amount of a good or service that consumers are willing and able to purchase at a give price and within a specific time period. Demand, on the other hand, is a broader concept that encompasses the entire relationship between price and quantity demanded
Ezea
ok
Shukri
how do you save a country economic situation when it's falling apart
Lilia Reply
what is the difference between economic growth and development
Fiker Reply
Economic growth as an increase in the production and consumption of goods and services within an economy.but Economic development as a broader concept that encompasses not only economic growth but also social & human well being.
Shukri
production function means
Jabir
What do you think is more important to focus on when considering inequality ?
Abdisa Reply
any question about economics?
Awais Reply
sir...I just want to ask one question... Define the term contract curve? if you are free please help me to find this answer 🙏
Asui
it is a curve that we get after connecting the pareto optimal combinations of two consumers after their mutually beneficial trade offs
Awais
thank you so much 👍 sir
Asui
In economics, the contract curve refers to the set of points in an Edgeworth box diagram where both parties involved in a trade cannot be made better off without making one of them worse off. It represents the Pareto efficient allocations of goods between two individuals or entities, where neither p
Cornelius
In economics, the contract curve refers to the set of points in an Edgeworth box diagram where both parties involved in a trade cannot be made better off without making one of them worse off. It represents the Pareto efficient allocations of goods between two individuals or entities,
Cornelius
Suppose a consumer consuming two commodities X and Y has The following utility function u=X0.4 Y0.6. If the price of the X and Y are 2 and 3 respectively and income Constraint is birr 50. A,Calculate quantities of x and y which maximize utility. B,Calculate value of Lagrange multiplier. C,Calculate quantities of X and Y consumed with a given price. D,alculate optimum level of output .
Feyisa Reply
Answer
Feyisa
c
Jabir
the market for lemon has 10 potential consumers, each having an individual demand curve p=101-10Qi, where p is price in dollar's per cup and Qi is the number of cups demanded per week by the i th consumer.Find the market demand curve using algebra. Draw an individual demand curve and the market dema
Gsbwnw Reply
suppose the production function is given by ( L, K)=L¼K¾.assuming capital is fixed find APL and MPL. consider the following short run production function:Q=6L²-0.4L³ a) find the value of L that maximizes output b)find the value of L that maximizes marginal product
Abdureman
types of unemployment
Yomi Reply
What is the difference between perfect competition and monopolistic competition?
Mohammed
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