Francesco S. Carta <entuland@gmail.com>, on 02/09/2010 00:38:27, wrote:
red floyd <redfloyd@gmail.com>, on 01/09/2010 15:11:59, wrote:
On Sep 1, 2:55 pm, Angus<anguscom...@gmail.com> wrote:
On 1 Sep, 22:51, "Francesco S. Carta"<entul...@gmail.com> wrote:
Angus<anguscom...@gmail.com>, on 01/09/2010 14:43:29, wrote:
I am trying to set the strategy (algorithm) used in a context by
template. Here is my context class (which is incorrectly
implemented):
template<class TStrategy>
class Context //TStrategy is the algorithm
{
private:
TStrategy * strategy_; //knows about StrategyInterface
public:
void execute() const
{
strategy_->execute();
}
};
The strategies:
class StrategyInterface
{
public:
virtual void execute() const = 0; //abstract class - interface
only
};
//the actual concrete algorithms
class ConcreteStrategyA: public StrategyInterface
{
public:
virtual void execute() const
{
cout<< "Called ConcreteStrategyA execute method"<< endl;
}
};
And I want to do something like this:
Context<ConcreteStrategyA> contextD;
contextD.execute();
But I need to initialise the context data member properly. how do I
do that?
I'm not sure about "how" you would do that, but I know "where" you
should do that: in a constructor. There is none in the code you
posted, why?
--
FSC -http://userscripts.org/scripts/show/59948
http://fscode.altervista.org-http://sardinias.com-Hide quoted text -
- Show quoted text -
I guess I just need to add this:
Context(){ strategy_ = new TStrategy; }
~Context() { delete strategy_; }
Could I do it without using the heap?
Not if you store a pointer, You defined stategy_ as a TStrategy*.
That's not necessarily true. One can get advantage from pointers and
references to delay or completely omit expensive constructions if not
immediately needed or if not needed at all, still avoiding to use
dynamic allocation.
Given:
class Expensive {
public:
Expensive() {
// some expensive init here
}
void execute() const {
//...
}
private:
// some expensive data here
};
One could do:
class Delayed {
public:
Delayed() : expensive(0) {}
void execute() const {
if (!expensive) set_expensive();
expensive->execute();
}
private:
mutable Expensive* expensive;
void set_expensive() const {
static Expensive exp;
expensive = &exp;
}
};
Although I would maybe implement it so:
class Delayed {
public:
void execute() const {
expensive().execute();
}
private:
Expensive& expensive() const {
static Expensive exp;
return exp;
}
};
will share the same Expensive instance. That was just an example to
illustrate my point.