Vault
4.1
|
00001 /* 00002 Copyright c1997-2014 Trygve Isaacson. All rights reserved. 00003 This file is part of the Code Vault version 4.1 00004 http://www.bombaydigital.com/ 00005 License: MIT. See LICENSE.md in the Vault top level directory. 00006 */ 00007 00010 #include "vclassregistry.h" 00011 00012 #include "vexception.h" 00013 00014 V_STATIC_INIT_TRACE 00015 00016 // VClassFactory ------------------------------------------------------------- 00017 00018 VClassFactory::VClassFactory(const VString& classID) 00019 : mClassID(classID) 00020 { 00021 } 00022 00023 bool VClassFactory::matchesClassID(const VString& classID) const { 00024 return mClassID == classID; 00025 } 00026 00027 void VClassFactory::getClassID(VString& classID) const { 00028 classID = mClassID; 00029 } 00030 00031 // VClassRegistry ------------------------------------------------------------ 00032 00033 // static 00034 VClassRegistry* VClassRegistry::gRegistry = NULL; 00035 00036 // static 00037 VClassRegistry* VClassRegistry::registry() { 00038 static bool initialized = false; // static, so will be executed 1st time only 00039 00040 // We're using the "create on first use" idiom here. 00041 if (! initialized) { 00042 gRegistry = new VClassRegistry(); 00043 initialized = true; 00044 } 00045 00046 return gRegistry; 00047 } 00048 00049 VClassRegistry::VClassRegistry() : 00050 mFactories() { // -> empty 00051 } 00052 00053 VClassRegistry::~VClassRegistry() { 00054 for (VSizeType i = 0; i < mFactories.size(); ++i) { 00055 delete mFactories[i]; 00056 } 00057 } 00058 00059 void* VClassRegistry::instantiateObject(const VString& classID) const { 00060 const VClassFactory* factory = this->findClassFactory(classID); 00061 00062 return factory->instantiateObject(); 00063 } 00064 00065 void VClassRegistry::registerClass(const VClassFactory* factory) { 00066 mFactories.push_back(factory); 00067 } 00068 00069 const VClassFactory* VClassRegistry::findClassFactory(const VString& classID) const { 00070 // FIXME: This would be a lot more efficient using a map instead of a vector. 00071 for (VSizeType i = 0; i < mFactories.size(); ++i) { 00072 if (mFactories[i]->matchesClassID(classID)) { 00073 return mFactories[i]; 00074 } 00075 } 00076 00077 throw VStackTraceException(VSTRING_FORMAT("Unable to find class factory for '%s' in class registry.", classID.chars())); 00078 } 00079