In my ongoing quest to master various design patterns, I ran into the "State" design pattern.
First, let me explain where I am attempting to use this pattern. I have a Form which I would like to apply state to. My program has three states: Configuration, Processing, and ProcessingComplete. When the Form changes state various components of the Form will become enabled/disabled, visible/invisible, etc.
With my understanding of the State pattern, all those changes (making components visible/invisible, enabled/disabled, etc) should occur within a separate class which contains an instance of the Form. If the various State classes are separate from the Form's class, the State classes can not access the Form's components. I feel that this leaves me with one of two options:
I feel that option (1) is bad form, but I feel that option (2) violates the spirit of the State pattern somehow. The other thought I had was use option (2) but using partial class implementations, however I still feel that its violating the spirit of the State pattern.
Are my feelings on either choice unjust, or is there another option I haven't even thought of?
You're missing a third option.
Include the parts the State will control as part of the contract of the class.
So if your goal is to modify the text of a label, your base State class should require a label be sent to it. Then you can have an InitializeState(State myState)
or BuildStates()
method on your form that sets the appropriate fields.
Option 1 is wrong. Option 2 really becomes unnecessary when you design your State such that it can only act what it is given, which is really how objects should act anyway.