The Programming Language Tips[9]

[入库:2005年8月19日] [更新:2007年3月24日]

本文简介:选择自 chelsea 的 blog

解决方法

慎重的在构造函数中调用虚函数,尤其是在java和c#中,至少应该在注释中说明理由


强制针对接口编程

问题

尽管“针对接口编程”做为一条原则已经广为流传,但实际应用中仍然随处可见hashmap,vector等做为接口参数、返回值传来传去

我见过的解决方法

使用factory method返回接口,并最小化具体类构造函数的访问权限,或类本身的访问权限

我推荐的解决方法

factory method依然值得推荐,另外可以利用语言本身的特性来避免多写一个factory method

在c++中,override一个虚函数时可以任意改变它的访问权限,包括将它由public变为private;有人说这样会破坏封装,但只要语义正确,有意为之,也没什么问题

在c#中,可使用“显式接口成员实现”

在java中,我不知道,讨论一下

[c++]

class isomeinterface

{

public:

     virtual void somemethod() = 0;

};

 

class someclass : public isomeinterface

{

private:

     void somemethod(){

         std::cout << "subclass\n";

     }

};

 

int main(int argc, _tchar* argv[])

{

     someclass obj;

     obj.somemethod();    //error

     isomeinterface& iobj = obj;

     iobj.somemethod();   //ok

     return 0;

}

[c#]

     public interface isomeinterface { 

         void somemethod();

     }

     public class someclass:isomeinterface {

         //1,不要写访问修饰符;2,使用方法全名

         void isomeinterface.somemethod(){

              system.console.writeline("subclass");

         }

}

     public class test{

         void test(){

              someclass obj = new someclass();

              obj.somemethod();    //error;

              isomeinterface iobj = obj;

              iobj.somemethod();   //ok

         }

     }

本文关键:The Programming Language Tips
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top