c++でStrategyパターンってこんな感じ? の小修正
main部分をもう少し手直ししてみた。しかしこれだと次にsha128の実装を行うときに3行も追加が必要となる。なるべくであれば追加は一行だけでうまくまわしたいものなのだけど、まだその手法がよく分からない。
68 Hash get_algorithms_map( string my_algorithm ) 69 { 70 typedef map<string, Hash> algorithms_map_t; 71 algorithms_map_t algorithms_map; 72 73 MD5_hash md5; 74 SHA1_hash sha1; 75 Hash md5_h( &md5 ); 76 Hash sha1_h( &sha1 ); 77 78 algorithms_map.insert( pair <string, Hash>( "md5" , md5_h ) ); 79 algorithms_map.insert( pair <string, Hash>( "sha1", sha1_h ) ); 80 81 algorithms_map_t::iterator p; 82 p = algorithms_map.find( my_algorithm ); 83 if ( p != algorithms_map.end()) 84 { 85 return (*p).second; 86 } 87 else 88 { 89 throw logic_error("not found"); 90 } 91 } 92 93 94 int main () 95 { 96 // 本当は引数とかでこの値を入れると思います。 97 string my_algorithm = "md5"; 98 Hash h = get_algorithms_map( my_algorithm ); 99 cerr << h.get_hash_("hoge") << endl; 100 return 0; 101 }