Reputation: 476
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.
Upvotes: 3
Views: 1844
Reputation: 1693
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:
State1A
and State1B
are ok as subclasses of State1
.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
Upvotes: 0
Reputation: 40036
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'
Upvotes: 3