简体   繁体   中英

Java State design pattern / "substates"

I'm coding in Java and I use the State design pattern like this example: http://onjavahell.blogspot.fr/2009/05/simple-example-of-state-design-pattern.html

However the UML I've got it's like this:

+---------+        +---------+ 
| Context |--------|  State  |
+---------+        +---------+ 
                        |
               +----------------+
               |                |
          +---------+       +---------+
          | State 1 |       | State 2 |
          +---------+       +---------+
               |
       +----------------+
       |                |
  +----------+       +----------+
  | State 1A |       | State 1B |
  +----------+       +----------+

I have "sub states". How can code it? Should I make abstract class the State 1 or is there any other way? Searching I didn't find any example like this.

What's the meaning of "Sub-state"? In State pattern, there is nothing that can be treated as "Sub-State". "State" is representing the state of the entity. Every state is a state. Unless you give a reasonable explanation on what you are trying to achieve, I believe you are thinking in something incorrect.

As long as all states shares the same base-class/interface, it will works. You may have inheritance relationships between states, it will still work and it has nothing to do with the state pattern. And, even you have inheritance relationships, they are still 'states', and not 'sub-states'

As always is a bit difficult to say without more information about the domain you are trying to model. However you may find to main cases:

  • That your states are disjoint and respond to the IS-A principle ( here you may find more detailed information and discussions about it). In that case State1A and State1B are ok as subclasses of State1 .
  • That your states can be combined, so that it makes sense to be in State1 options A and B and in State2 , options A and B. Although not a common case, this sometimes happens and it means that your object actually has two types of states. How to handle this depends a lot on the interaction between the states; if they are independent, then you can model them as separate hierarchies. If they are dependent on their behavior, then the State class can in turn have an inner state A and B .

As I said, the second case is rare, but in some designs it happens.

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM