Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <time.h>
- class BaseClass;
- int randomInt(int max = 0) {
- srand(time(NULL) + rand());
- if(max == 0) {
- return rand();
- } else {
- return rand() % max;
- }
- }
- class Factory {
- public:
- virtual BaseClass* create() = 0;
- };
- class BaseClass {
- protected:
- class BaseClassFactory;
- public:
- virtual void method() = 0;
- static Factory *getFactory() {
- return new BaseClassFactory;
- }
- protected:
- class BaseClassFactory : public Factory {
- public:
- BaseClass* create() {
- return NULL;
- }
- };
- };
- class DerrivedClass : public BaseClass {
- protected:
- class DerrivedClassFactory;
- public:
- void method() {
- std::cout << "Derrived Class!" << std::endl;
- }
- static Factory *getFactory() {
- return new DerrivedClassFactory();
- }
- protected:
- class DerrivedClassFactory : public Factory {
- public:
- BaseClass* create() {
- return new DerrivedClass();
- }
- };
- };
- class SecondDerrivedClass : public BaseClass {
- protected:
- class SecondDerrivedClassFactory;
- public:
- void method() {
- std::cout << "SecondDerrived Class!" << std::endl;
- }
- static SecondDerrivedClassFactory* getFactory() {
- return new SecondDerrivedClassFactory();
- }
- protected:
- class SecondDerrivedClassFactory : public Factory {
- public:
- BaseClass *create() {
- return new SecondDerrivedClass();
- }
- };
- };
- class ClassCreator {
- public:
- void subscribeFactory(Factory *f) {
- mClassFactoryList.push_back(f);
- }
- void clearSubscriptions() {
- std::vector<Factory*>::iterator itr;
- for(itr = mClassFactoryList.begin(); itr != mClassFactoryList.end();) {
- delete (*itr);
- itr = mClassFactoryList.erase(itr);
- }
- }
- BaseClass *createRandomClass() {
- return mClassFactoryList.at(randomInt(mClassFactoryList.size()))->create();
- }
- private:
- std::vector<Factory*> mClassFactoryList;
- };
- int main() {
- ClassCreator *c = new ClassCreator();
- c->subscribeFactory(DerrivedClass::getFactory());
- c->subscribeFactory(SecondDerrivedClass::getFactory());
- BaseClass *b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- b = c->createRandomClass();
- b->method();
- delete b;
- c->clearSubscriptions();
- delete c;
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment