Reputation: 7611
I'm currently working on a WPF C# system where there a number of 'Process' modes, such as Guillotine
or Turretting
. For each of these modes, an action
can be performed against each job
currently at that mode - this can be Start
, Stop
, Pause
, Resume
and Complete
.
Currently I have a base class for the 'JobAction', and classes for Start
, Stop
etc which extend that. Inside the base class I have an if statement to check the current process.
This seems like it could be vastly improved, but I don't know how to design it. Any ideas?
Upvotes: 0
Views: 107
Reputation: 12956
Replace the process if
with the decorator pattern.
You'll decorate JobAction
with a GuillotineProcessDecorator
or TurrettingProcessDecorator
. You could decide which decorator to use at the composition root using an IoC container such as SimpleInjector
.
The decorator pattern allows you to add functionality to an object without the rigidity of typical class hierarchies. So you can easily add further Processes in the future and combine processes.
The decorator pattern:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
An implementation would look something like:
public abstract class JobActionBase
{
public abstract void Start() {}
public abstract void Stop() {}
public abstract void Pause() {}
public abstract void Resume() {}
public abstract void Complete() {}
}
public class JobAction : JobActionBase
{
public void Start() {}
public void Stop() {}
public void Pause() {}
public void Resume() {}
public void Complete() {}
}
public abstract class Decorator : JobActionBase
{
protected JobActionBase jobAction;
public void Decorate(JobActionBase jobAction)
{
this.jobAction = jobAction;
}
public override void Start()
{
if (jobAction != null)
{
jobAction.Start();
}
}
}
public class GuillotineProcessDecorator : Decorator
{
public override void Start()
{
base.Operation();
// Do something that's Guillotine specific
}
}
// Encapsulate this in a factory
JobAction jobAction = new JobAction();
GuillotineProcessDecorator d = new GuillotineProcessDecorator();
d.Decorate(jobAction);
d.Sale();
Upvotes: 1