例子:
class Modem
{
public:
virtual void Dial(CString pno) =0;
virtual void Handup() =0;
virtual void Send(char c) =0;
virtual void Recv() = 0;
virtual accept(ModemVisitor v)=0;
};
class HayesModem :public Modem
{
public:
void Dial(CString pno){}
void Handup(){}
void Send(char c) {}
void Recv() {}
virtual accept(ModemVisitor v)
{
v.visit(this);
}
};
class ZoomModem:public Modem
{
public:
void Dial(CString pno){}
void Handup(){}
void Send(char c){}
void Recv(){}
virtual accept(ModemVisitor v)
{
v.visit(this);
}
};
class ModemVisitor
{
public:
void visit(HayModem modem) = 0;
void visit(ZoomModem modem) = 0;
};
class ModemCfg :public ModemVisitor
{
public:
void visit(HayerModem modem)
{
printf("I am HayerModem!");
}
void visit(ZoomModem modem)
{
printf("I am ZoomModem!");
}
};
void main()
{
ModemCfg* pm = new ModemCfg();
HayerModem* ph = new HayerModem();
ZoomModem* pz = new ZoomModem();
vector
vectmodem;
vectmodem.push_back (ph);
vectmodem.push_back (pz);
for(int i = 0;i< vectmodem.size();i++)
{
((Modem*)vectmodem[i]).accept(pm);
}
vectmodem.clear();
}