R
R
rvller2011-08-04 01:45:25
Programming
rvller, 2011-08-04 01:45:25

Responding to a change in the state of an object

An interesting question is how would you implement the ability to add a certain handler (method) when the state of the object changes.

For example, we have a class:

class car {
private Engine engine;
private CarType carType;
...

public void setEngine(Engine engine) {
this.engine = engine;
}

public void setCarType(Engine carType) {
this.carType= carType;
}
}


I would like to be able to execute a certain method (for example, the calculateCarCost () method) if any (some) member of this class changes.

In the wrong solution, it would look like this:

class car {
private Engine engine;
private CarType carType;
...

public void setEngine(Engine engine) {
this.engine = engine;
calculateCarCost()
}

public void setCarType(Engine carType) {
this.carType= carType;
calculateCarCost()
}

public void calculateCarCost() {
...
}
}


The language doesn't matter, the idea matters.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey Grichenko, 2011-08-04
@Kalobok

Why is the given solution wrong? Replace calculateCarCost with some updateObject and get something like what is usually done in such a situation.

S
Sergey Beresnev, 2011-08-04
@sectus

Probably worth learning about [google]Design Patterns[/google]. In this case, this one is suitable: Observer

V
Vladimir Chernyshev, 2011-08-04
@VolCh

If flexibility (other methods, including other objects, more than one method, etc.) is not important, then a completely normal solution, IMHO. The only caveat is that you are tracking the assignment, not the change. Following the letter of the task and abstracting from the language, before assigning and calling, you first need to compare whether the same value is assigned and, accordingly, the method is called once again, and if not, then do not assign or call.

A
Anatoly, 2011-08-04
@taliban

You have a very good solution. If you want some calculateCarCost method to be called by itself, then you will not succeed, you need to call it manually, although if you are not interested in the language:


class Car
{
    protected function A()
    {
    }

    protected function B()
    {
    }
    
    protected function Calculate()
    {
    }

    public function __call($func, $args)
    {
        call_user_func_array(array($this, $func), $args);
        $this->Calculate();
    }
}

I don't know if there is such a possibility in c++, but the bottom line is that methods are not called directly, but through an intermediary method. Although in your case, I would leave everything as it is =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question