Josh Dybnis on 13 Jul 2003 18:11:01 -0000 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
[ALACPP] abstract factories in C |
This is how I would do an abstract factory in C: Soldier *MakeSillySoldier(void); Monster *MakeSillyMonster(void); SuperMonster *MakeSillySuperMonster(void); Soldier *MakeBadSoldier(void); Monster *MakeBadMonster(void); SuperMonster *MakeBadSuperMonster(void); typedef struct EnemyFactory { Soldier *(*MakeSoldier)(void); Monster *(*MakeMonster)(void); SuperMonster *(*MakeSuperMonster)(void); } EnemyFactory; EnemyFactory easyLevelEnemyFactory = { MakeSillySoldier, MakeSillyMonster, MakeSillySuperMonster }; EnemyFactory dieHardLevelEnemyFactory = { MakeBadSoldier, MakeBadMonster, MakeBadSuperMonster }; Note that is easy to define, and it is granular, because you can pass in indivual elements of the struct to different modules. Unfortunately this does not work as well in C++, because it breaks with inheritance. The problem is that covariant return types only apply to method overloading, not type conversion. So this is fine: struct A { A *foo(); }; struct B : A { B *foo(); }; // ok, overriding foo with a derived return type But this is not: A *(*a)() = 0; B *(*b)() = 0; a = b; // invalid conversion, even though b's return type is dirived from a's -Josh Dybnis _______________________________________________ alacpp mailing list alacpp@xxxxxxxxxxx http://lists.ellipsis.cx/mailman/listinfo/alacpp