Answer the question
In order to leave comments, you need to log in
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;
}
}
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() {
...
}
}
Answer the question
In order to leave comments, you need to log in
Why is the given solution wrong? Replace calculateCarCost with some updateObject and get something like what is usually done in such a situation.
Probably worth learning about [google]Design Patterns[/google]. In this case, this one is suitable: Observer
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.
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();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question