class B {
public:
B(int n):data(n) { }
int Data( ) const { return data; }
void g1( );
void g2( );
void g3( );
private:
const int data;
};
void f( B& b ) {
int condition = b.Data( );
if(condition == 1) { b.g1( ); }
else if(condition == 5) { b.g2( ); }
else if(condition == 9) { b.g3( ); }
}
当把此程序交给用户试用时, 针对函数f, 用户提出了一项新的要求: 当condition为100时, 依次执行b的成员函数g1( )和g2( )。经过进一步了解, 小王获悉: 以后可能还要增加处理condition的值是其它数值时的情况, 但这些需要分别处理的不同条件值的个数肯定不多。小王希望他写出的代码既能满足上述要求, 又不用每次都改写f的代码。请你帮小王重新设计, 使得新设计能够满足小王的愿望。简要说明你的设计思想, 给出实现代码。
class B {
public:
B(int n):data(n) {}
int Data( ) const {return data;}
void g1( ) { cout<<"g1"<<endl; }
void g2( ) { cout<<"g2"<<endl; }
void g3( ) { cout<<"g3"<<endl; }
virtual void g()=0;
private:
const int data;
};
class B1:public B
{
public:
B1():B(1){}
virtual void g()
{
g1();
}
};
class B5:public B
{
public:
B5():B(5){}
virtual void g()
{
g2();
}
};
class B9:public B
{
public:
B9():B(9){}
virtual void g()
{
g3();
}
};
class B100:public B
{
public:
B100():B(100){}
virtual void g()
{
g1();
g2();
}
};
void f( B& b ) {
b.g();
}
int main()
{
B1 b1;
f(b1);
B5 b5;
f(b5);
B9 b9;
f(b9);
B100 b100;
f(b100);
return 0;
}