From: sheepman Date: 2002-01-31T20:41:03+09:00 Subject: Re: Policy Classes - Challenge Hello. On Thu, 31 Jan 2002 11:38:41 +0900 John Carter wrote: > Alexandrescu's book Modern C++ Design > http://cseng.aw.com/book/0,3828,0201704315,00.html > describes (See the "Sample Chapter" link) the concept of Policy Classes. > > I see this, like the laser was, a "Solution looking for a problem". > > Basically it is the idea that the client of a library should... > * Not be forced to inherit from library objects. > * Should be able to plug in any suitable class provided by the > client or the library as the base class of a library class. > * Should be able to plug in several orthoganal policy classes as > multiply inherited base classes. > > He does all this magic by doing arcane things with C++ templates. (Michael > Feathers mostly wondrously called the book "Porn for Programmers".) > I'm reading the book in translation. His C++ template magic is great and a little complicated. > Question. Can you think of a neat and compelling use for this concept, I'm > prepare to write the code as a proof of concept. How about this? It uses [] like template in C++ class PolicyPattern def self.[](*mod) @klass_with_policy ||= {} unless @klass_with_policy[mod] klass = self.dup make_klass_include_modules(klass, mod) @klass_with_policy[mod] = klass end return @klass_with_policy[mod] end def self.make_klass_include_modules(klass, mods) class << klass def include__(m) include(m) end end mods.each{|mod| klass.include__(mod) } class << klass remove_method :include__ end end private_class_method :make_klass_include_modules end class HostClass < PolicyPattern end module PolicyHoge def some_method puts "hoge" end end module PolicyBar def some_method puts "bar" end end HostClass[PolicyHoge].new.some_method #=> hoge HostClass[PolicyBar].new.some_method #=> bar -- sheepman / TAMURA Takashi sheepman@tcn.zaq.ne.jp http://www.tcn.zaq.ne.jp/sheepman/ Key fingerprint = 4E13 FE38 CD73 48D3 38AE 00EE 9E28 F98B D569 848E