Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What design pattern is best employed to control a sequence of steps?

I have a winform tool that interfaces with hardware using a serial port.

The serial port is used to send commands to the the hardware, which will acknowledge the commands and sometimes return data.

To accomplish a task, several commands need to be sent to the hardware in a defined order.

I have successfully implemented the tool using a switch statement to control the sending of the commands. However, while this works, I can't help thinking that there is a better, more OO way of doing this - is there?

Current implementation is below:

Each case is a command that needs sending to the hardware. Send method is passed a method to invoke and the ID of next step - which will be returned if command sent successfully.

  • Tool will send a start session command to the hardware.
  • Hardware acknowledges command.
  • Tool sends a set direction command to the hardware.
  • Hardware will acknowledge command.

etc.

MessageID nextStep = MessageID.IMS;

while (nextStep != MessageID.Stop)
{
    switch (nextStep)
    {
        case MessageID.ISS:
            nextStep = Send( new ISS_StartSession(), MessageID.IE386);
            RaiseProgressEvent(10); //percentage complete
            break;

        case MessageID.IE386:
            nextStep = Send( new IE386_SetDirection(Direction.BOTH), MessageID.IE378);
            RaiseProgressEvent(20);
            break;

       //etc

       case MessageID.Error:
            HandleError(); //abort task if necessary
            break;
    }
 }

Is there a better way to do this..?

Is there a well known design pattern I should look at?

like image 281
Kildareflare Avatar asked Jan 20 '11 14:01

Kildareflare


1 Answers

Looks like a State Machine. There are lots of resources on the net about them. Have a look.

http://en.wikipedia.org/wiki/Abstract_state_machines

like image 84
Chris Kooken Avatar answered Oct 10 '22 21:10

Chris Kooken