jeudi 20 septembre 2018

Design Pattern for object alteration recognition in C++?

I'm looking for a mechanic/design pattern, which allows to set up an object in a way, so that the mechanic notices if the object is altered after a certain point of existence (for example construction). Ideally the object would be able to get information about its alteration, as well.

I'm imagining a sort of smart-pointer and/or interface, which notes write access and communicates that to the object.

Possible Use Case: Objects, whose contents have been loaded from file, shall be written to file if altered when destructed.

Trivially you could just implement all setters of the object to count write accesses individually.

class A
{
    string filename;
    unsigned int altered;
    int m_a, m_b, M_c;
public:
    A(string filename) : filename(filename), altered(0) { /* parse file */ }
    ~A() { if(altered) {/* write out to file */} } 

    void setA(int a) {altered++; m_a = a}
    void setB(int b) {altered++; m_b = b}
    void setC(int c) {altered++; m_c = c}
};

This I find quite hard to maintain and not very elegant. Also such a solution is not very portable to other kinds of objects.

Aucun commentaire:

Enregistrer un commentaire