Answer the question
In order to leave comments, you need to log in
Pattern Strategy
I have a small question about this template. I read the article habrahabr.ru/blogs/programming/132929/ It seems that I even understood what was happening. I'm trying to make it work, but it doesn't work. The point is that the examples simply call a method from another class that outputs a text string. In my case, it is required that the called method changes the parameters of the main class object. That is, like this:
class changeValue
{
public:
changeValue();
~changeValue();
virtual void Change() = 0;
};
changeValue::changeValue() {}
changeValue::~changeValue() {}
class General
{
public:
General();
~General();
float a;
void changeit();
changeValue *object;
};
General::General() {a=0;}
General::~General() {}
void General::changeit()
{
object->Change();
}
class changeValueTo1 : public changeValue
{
changeValueTo1();
~changeValueTo1();
void Change();
};
changeValueTo1::changeValueTo1() {}
changeValueTo1::~changeValueTo1() {}
void changeValueTo1::Change()
{
//должен изменить значение параметра a объекта класса MyClass на 1
}
class MyClass : public General
{
MyClass();
~MyClass();
};
MyClass::MyClass() {
object = new changeValueTo1;
}
MyClass::~MyClass() {
delete object;
}
Answer the question
In order to leave comments, you need to log in
How to implement the void changeValueTo1::Change() method so that it has access to the parameters of the MyClass class?
The easiest way, as already said, is to make a cross reference / pointer.
class changeValueTo1 : public changeValue
{
public:
changeValueTo1(General * p) : _parent(p) {}
~changeValueTo1() {}
void Change();
private:
General * _parent;
};
void changeValueTo1::Change()
{
//должен изменить значение параметра a объекта класса MyClass на 1
_parent->a = 5;
}
MyClass::MyClass() {
object = new changeValueTo1(this);
}
You need a cross-reference, although it is not the best option, often the cause of leaks, but is a strategy mandatory? In general, I personally try to adhere to the rule: “it’s easier to write easier, then it will be easier to maintain and it will be easier to finish writing.”
If you need to somehow modify the context from the strategy, then most likely you have incorrectly decomposed classes and most likely violated the Single Responsibility Principle .
Roughly speaking, you should have a separate context class and a separate class from the domain, whose objects are processed by the strategy. And then it can be easily thrown into the strategy, for example, through method arguments.
In general, you need to look at the original problem, with a high degree of probability, the strategy is really not needed there, but simple polymorphism is needed (most likely you have a case where the strategy is one of the behaviors of some class, and not an external algorithm).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question