作者legnaleurc (CA)
看板C_and_CPP
標題Re: [問題] template一問
時間Sat Jun 18 18:32:30 2011
※ 引述《NIKE74731 (做遊戲的心)》之銘言:
: class Base
: {
: public: virtual void Run() = 0;
: };
: Base* Get( int iType )
: {
: switch( iType )
: {
: case 1:
: return new D1;
: break;
: case 2:
: return new D2;
: break;
: case 3:
: return new D3;
: break;
: }
: }
class Factory {
public:
typedef std::function< Base *() > Creator;
static Base * Create( int id );
static bool Register( int id, Creator c );
private:
static std::map< int, Creator > f_;
};
Base * Factory::Create( int id ) {
std::map< int, Creator >::const_iterator it = f_.find( id );
if( it == f_.end() ) {
return NULL;
}
return it->second();
}
bool Register( int id, Creator c ) {
if( f_.find( id ) != f_.end() ) {
return false;
}
f_.insert( std::make_pair( id, c ) );
return true;
}
// register
Factory::Register( 1, []() {
return new D1;
} );
Factory::Register( 2, []() {
return new D2;
} );
Factory::Register( 3, []() {
return new D3;
} );
// create instance
int i;
std::cin >> i;
Base * obj = Factory::Create( i );
很陽春的 factory pattern
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 175.96.119.92
→ karcher:有一股懷念的感覺.... 06/18 21:46
推 VictorTom:囧rz 連語法都看不懂....(逃XD) 06/19 13:15