This is a discussion on Composite, State or Strategy? Not again!.. within the Software Patterns forums, part of the Testing category; Hi there, I have a class "Task" that *can* contain many subtasks. Various aspects of the Tasks behaviour ...
|
|||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Composite, State or Strategy? Not again!..
Hi there,
I have a class "Task" that *can* contain many subtasks. Various aspects of the Tasks behaviour change depending upon whether it contains subtasks or not. Currently these varying behaviours are implemented using "if-else" statements within each method. For example: public TimeSpan GetDuration() { if ( this.subTasks.count > 0 ) { return sumOfMySubtasksDurations(); } else { return myDuration; } } There is lots of this type of thing going on. I'm at the stage where the class is 300+ lines of code long and I'm thinking of breaking it down. My obvious choice is to create two State objects for the Task - CompositeTaskState and LeafTaskState. The task will assign itself a new state every time a subtask is added or removed, at runtime. This will create something like the following: public TimeSpan GetDuration() { return myState.GetDuration(); } The state itself might be added in the following way: public void AddSubtask( Task t ) { subTasks.Add( t ); myState = new CompositeTaskState( this ); } public void RemoveTask( int i ) { this.subTasks.RemoveAt( i ); if ( subTasks.Count == 0 ) { myState = new LeafTaskState(); } } You get the idea. I had considered a kind-of-strategy pattern, but this would mean me creating many strategy patterns for only one single axis of change - somewhat overkill. Similarly, I would have considered composite, except this doesn't allow for runtime changes or behaviour? Or does it!? Any thoughts apprecitated? Tobes |