Chaining commands

N

notme

Hi, I'm using something similar to command pattern. I have an abstract base
class Command,
with some methods, and then some implementations: CmdOpen, CmdRead,
CmdClose, etc.
It works ok, but now I need to chain commands. The most obvious approach is
adding
a chain function, so if I need to do this sequence: open, read, close, I'd
do:
open->chain(read);
read->chain(close);

also possibly some class needs to set some parameter, so in fact this turns
to be:
read->setbuffer(buf);
open->chain(read);
read->chain(close);

This would create a linked list of commands. What I'm wondering is if there
something more
readable than this, basically some way to make it look like:
open [op] read [op] close; where [op] would denote some operator or
whatever.

Thanks!
 
M

Mike Wahler

notme said:
Hi, I'm using something similar to command pattern. I have an abstract base
class Command,
with some methods, and then some implementations: CmdOpen, CmdRead,
CmdClose, etc.
It works ok, but now I need to chain commands. The most obvious approach is
adding
a chain function, so if I need to do this sequence: open, read, close, I'd
do:
open->chain(read);
read->chain(close);

also possibly some class needs to set some parameter, so in fact this turns
to be:
read->setbuffer(buf);
open->chain(read);
read->chain(close);

This would create a linked list of commands. What I'm wondering is if there
something more
readable than this, basically some way to make it look like:
open [op] read [op] close; where [op] would denote some operator or
whatever.

You can have your member functions return a reference to the object
for which they're called. Then you can 'chain' those function calls,
the same way as e.g. the stream types use '>>' and '<<'.

class C
{
public:
const C& op1()
{
/* do something */
return *this;
}

const C& op2()
{
/* do something */
return *this;
}

const C& op3()
{
/* do something */
return *this;
}
};

int main()
{
C obj;
obj.op1().op2().op3();
return 0;
}

If you like, you can overload most of the built-in operators to suit
your preferred syntax.

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,635
Latest member
SkyePurves

Latest Threads

Top