vendredi 5 février 2016

Is there a pattern to track currently selected item in a container? Does state fits here?

My original project is complex but I wrote a small demo which illustrates the problem and my question.

My model contains a list of objects. When I call its method increment(), it is applied to the current selected item. My question is how should I track the currently selected item?

My code below uses a pointer currentItem to track the current selected item. But my real project has do/undo functionality via command pattern so it needs to track. Additionally I have more states there to keep track of including current selected item and previous selected item.

Besides the code below, I have tried state design pattern but than I have to implement alot of the functions in the strategy that applies to the object and seems to complicate things. Is there a specific pattern for this? Does strategy suits here or is an overkill or perhaps simple plain pointer approach is fine? Please keep in mind my application needs to support do/undo functionality.

#include <QCoreApplication>
#include <iostream>
#include <QList>


#define ITEM_COUNT  5

using namespace std;

class ObjectA {
public:
    ObjectA(string n, int p) {
        name = n;
        price = p;
    }

    string name;
    int price;

    void increment() {
        price++;
    }
};

class ContainerObject
{
public:
    QList<ObjectA*> items;

    ContainerObject() {
        for (int i = 0; i < ITEM_COUNT; i++)
        {
            string name = ("name " + std::to_string((_ULonglong)i));
            ObjectA * item = new ObjectA(name, 0);
            items.append( item );
        }

        // assume at index 3 is current item
        setCurrentItem( items.at(2) );
    }

    ObjectA* currentItem;

    void setCurrentItem(ObjectA * obj) {
        currentItem = obj;
    }

    void increment(){
        currentItem->increment();

        if( currentItem->price >= 2)
            setCurrentItem( items.at( 4) );
    }

    void print()
    {
        for (int i = 0; i < ITEM_COUNT; i++)
        {
            ObjectA * item = items.at( i );
            cout << item->name << "  " << item->price << " added" << endl;
        }

        cout << endl;
    }

};


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    ContainerObject container;

    // initial values
    container.print();

    container.increment();
    container.print();

    container.increment();
    container.print();

    container.increment();
    container.print();

    return a.exec();
}

Aucun commentaire:

Enregistrer un commentaire