facadeパターン
boost.iterator_facadeのコードを真似て、lattice_systemを実装してみた。
かなりトリッキーなコードだけど、結構使えそうなパターンだな。
下手なデザインパターンの教科書を読むより、コードを読んだ方がいろんなパターンが勉強できて面白い。
#include <iostream> #include <string> using namespace std; struct core_access { template <class Facade> static string class_name(const Facade& f){ return f.class_name(); } }; template <class Derived> class facade { private: const Derived& derived(){ return *static_cast<Derived*>(this); } public: void hello(){ cout << "This is class " << core_access::class_name(derived()) << endl; } }; class foo : public facade<foo> { private: friend class core_access; string class_name() const { return string("foo"); } }; class bar : public facade<bar> { private: friend class core_access; string class_name() const { return string("bar"); } }; int main(){ foo a; bar b; a.hello(); // => This is class foo b.hello(); // => This is class bar return 0; }
という感じ。
*static_cast<Derived*>(this);
の部分は、facadeが定義されている時点ではDerivedの定義は完了していないのでこんな形になっているのだろう。
privateメンバへのアクセスにcore_accessをかませる所もいい設計だと思う。