Using Queue with multiple class objects

Giganews Newsgroups
Subject: Using Queue with multiple class objects
Posted by:  Anders Eriksson (andis…@gmail.com)
Date: Wed, 26 Nov 2014

I need to have a Queue that contains a number of commands[1]. There are
three different command types and I wonder if this is the way to do this
or if there is a smarter way?

I have created an abstract class that has the type of command.
Then I created three subclasses that sets the type and adds the specific
properties for this command. See code below.

adding to queue
QDocCmd dCmd = new QDocCmd();
dCmd.InternalFileName = "doc.xlp";
dCmd.Linked = false;
_cmdQueue.Enqueue(dCmd);

extract from queue
foreach (QCommand qc in _cmdQueue)
{
    if (qc.QType == CmdType.Document)
        {
        QDocCmd cmd = (QDocCmd)qc;
        ...
    }
    ...
}

// Anders
[1] The commands are function calls to a hardware device.

namespace MyCommands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    public enum CmdType
    {
        Tilt,
        Move,
        Document
    }
    /// <summary>
    /// Class for Command data in queue
    /// </summary>
    public abstract class QCommand
    {
        public CmdType QType { get; set; }
        abstract public bool Run();
    }
    public class QDocCmd : QCommand
    {
        public QDocCmd()
        {
            QType = CmdType.Document;
        }
        public string InternalFileName { get; set; }
        public bool Linked { get; set; }
        
        override public bool Run()
        {
            bool result = true;
            
            result = DoDocument();

            return result;
        }
    }
    public class QMoveCmd : QCommand
    {
        public QMoveCmd()
        {
            QType = CmdType.Move;
        }
        public double R { get; set; }
        public double X { get; set; }
        public double Y { get; set; }
        public double Z { get; set; }
        
        override public bool Run()
        {
            bool result = true;
            
            result = DoMove();

            return result;
        }

    }
    public class QTiltCmd : QCommand
    {
        public QTiltCmd()
        {
            QType = CmdType.Tilt;
        }
        public double Angle { get; set; }
        
        override public bool Run()
        {
            bool result = true;
            
            result = DoTilt();

            return result;
        }

    }
}

--
English isn't my first language.
So any error or strangeness is due to the translation.
Please correct my English so that I may become better.

Replies