在类层次中增加一个虚拟函数(或一组函数),但不能改变基类,已知基类中有1个接口函数

class Base //基类

{

public:

 virtual void Accpet(Interface& Inter)=0;

};

class  Interface //中间层

{

public:

 void doSomething(Base_A& A)=0;

 void doSomething(Base_B& B)=0;

 void doSomething(Base_C& C)=0; 

};

///

class Base_A : public Base

{

public:

 void dongA() {printf("this is Base_A/r/n");}

 void Accpet(Interface& Inter) {Inter.doSomething(*this);}

};

class Base_B : public Base

{

public:

 void dongB() {printf("this is Base_B/r/n");}

 void Accpet(Interface& Inter) {Inter.doSomething(*this);}

class Base_C : public Base

{

public:

 void dongC() {printf("this is Base_C/r/n");}

 void Accpet(Interface& Inter) {Inter.doSomething(*this);}

};

通过一个中间层 我们可以是实现

class  Interface_A : public Interface

{

public:

 void doSomething(Base_A& A)

 {

  A.dongA(); 

 }

 void doSomething(Base_B& B)

 {

  B.dongB(); 

 }

 void doSomething(Base_C& C)

 {

  C.dongC(); 

 }

};

调用

void ClassName(Base& value)

{

 value.Accpet(Interface());

}

int _tmain(int argc, _TCHAR* argv[])

{


 Base_A A;

 Base_B B;

 ClassName(A);

 ClassName(B);

 return 0;

}

这样可以根据需要从interface派生出不同的中间层,在不改变基类的同时,可以实现给派生类加上同一类的函数