[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[jfriends-ml 11950] Re: 「アジャイル ソフトウェア開発の奥義 」第八回議事録案)



  高橋(智)です。

kurino@xxxxxxxxxxxxxxxxxxxxxx wrote:
snip 
>         Q. 「private な virtual ?」
>                 なぜ、public/protected でない ?
>                 どうゆう意味があるの ?
>                         Q. 毎回実装 ?
>                                 だから Header/Fodder のみ
snip

  上記の部分ですが、最近読んでいる
  「Effective C++ Third Edition」
     http://www.amazon.co.jp/exec/obidos/ASIN/0321334876
のItem35に記述が有りましたので、一部抜粋してご紹介します。
  (※このItem35のトピックは、Second Edition には有りませんでした)

-- 一部抜粋して引用 -------------------------------------------------
[Item35: Consider alternative to virtual function]
 ...
 <略>
   class GameCharacter {
   public:
    virtual int healthValue() const; // return character's health rating;
    ...                              // derived classes may redefine this
   };                                 
 <略>
 ...
 [The Template Method Pattern via the Non-Virtual-Interface Idiom]
   We'll begin with an interesting school of thought that argues
  that virtual functions should almost always be private. Adherents
  to this school would suggest that a better design would retain
  healthValue as a public member function but make it non-virtual
  and have it call a private virtual function to do the real work,
  say, doHealthValue:
   class GameCharacter {
   public:
    int healthValue() const         // derived classes do not redefine this
    {                               // see Item36
      ...                           // do "before" stuff - see below 
      int retval = doHealthValue(); // do theereal work
      ...                           // do "after" stuff - see below 
      return retval;
    }
    ...
   private: 
    virtual int healthValue() const; // derived classes may redefine this
    {
      ...          // default algorithm for calculating character's health
    }
   };                                 
 ...
 <略>
 ...
   This basic design -- having clients call private virtual functions
  indirectly through public non-virtual member functions -- is known as
  the non-virtual interface(NVI) idiom. It's a particular manifestation
  of the more general design pattern called Template Method(a pattern
  that, unfortunately, has nothing to do with C++ templates). I call the
  non-virtual function(e.g., healthValue) the virtual function's wrapper.
   An advantage of the NVI idiom is suggested by the "do 'before' stuff"
  and "do 'after' stuff" comments in the code. Those comments identify
  code segments guaranteed to be called before and after the virtual
  function that does the real work. ...<略>... There's not really any good
  way to do that if you let clients call virtual functions directly.
 ...
 <略>
 ...
--------------------------------------------------------------------

-- 
高橋智宏
  Java読書会( http://www.javareading.com/bof/ )