dimanche 20 novembre 2016

Object of Class A as member in class B. B requires object of A to initialize itself

If B just want to help A for something, is there a better way to implement it as opposed to what you are seeing below?

What design pattern this kind of code fits in? Is it owner pattern or helper pattern?

I don't have proper example to represent the relationship between A and B.

class A {
    B* b;
    int y;

    A()
    {
        y = 0;
        b = new B(this);
    }
    A(int z)
    {
        y = z;
        b = new B(this);
    }

public:
    void UpdateB(int s)
    {
        b->setX(s);
    }

    int getY()
    {
        return y;
    }
};

class B {
    A* a;
    int x;

    B()
    {
        x = 0;
        a = null;
    }
    B(A* aobj, int i)
    {
        x = i;
        a = aobj;
    }

public:
    void setZ(int u)
    {
        if (a && a->getY() != 0)
            x = u*a->getY();
        else
            x = 0;
    }
};

Aucun commentaire:

Enregistrer un commentaire