Sunday, June 24, 2007
consider alternatives to virtual functions
the template method pattern via the non virtual interface idiom
write a public function that does the before work ( taking a lock, checking conditions) , calls a virtual fn to do the work and than does after work ( logging etc). generally that virtual fn is private ? why?
general design is clients call private virtual functions through public non virtual member functions- is known as the non virtual interface idiom.
non virtual function is like the virtual function wrapper.
note that derived classes redefine private virtual functions ? it says that is ok...but i am not convinced?
what if some library class has virtual and then we inherit and accidently override that function.
what if you just declare a virtual function without virtual in a derived class without he qualifier ??
the strategy pattern via function patterns
pass a function pointer with the defined type that is stored. and then call that function.
note that using the function pointer to calculate the health means that you need to weaken the encapsulation and provide either public accessors or make it a friend function.
strategy pattern via tr1::function pointer
why health calculator shud be a function and not something that just acts like a function.
you can use the tr1::bind function to bind an argument to a function.
the classic strategy pattern
standard pattern.
to calculate health of a object , have a separate hierarchy of calculation functions, and keep an object of these calculation functions inside the object.
summary:
use the non virtual interface idiom. a form of the template method design pattern that wraps public non virtual member functions around less accessible virtual functions.
replace virtual functions with function pointer data members, a stripped down manifestation of the strategy design pattern
replace virtual functions with tr1::function data members thus allowing use of any callable entity with a signature compatible with what you need. this too is a form of the strategy design pattern
replace virtual functions in one hierarchy with virtual functions in another hierarchy. this is the conventional implementation of the strategy design pattern
things to remember:
alternative to virtual functions include the nvi idiom and various forms of the strategy desing pattern the nvi idiom is itself an example of the template design pattern
a disadvantage of moving functionality from a member function to a function outside the class is that the non member function lacks access to the class's non public members
tr1::function objects act like generalized function pointers, such object support all callable entities compatible with a given target signature
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment