1 /* 2 * Copyright (C) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef CLASS_CREATOR_H 17 #define CLASS_CREATOR_H 18 19 #include <map> 20 #include <string> 21 22 namespace OHOS { 23 namespace bluetooth { 24 using ClassCreateFun = void *(*)(void); 25 26 class ClassFactory { 27 public: 28 static void RegisterClass(const std::string &name, ClassCreateFun func); 29 static void *NewInstance(const std::string &name); 30 31 private: 32 static std::map<std::string, ClassCreateFun> g_register; 33 }; 34 35 class ClassRegister { 36 public: ClassRegister(const std::string & name,ClassCreateFun func)37 ClassRegister(const std::string &name, ClassCreateFun func) 38 { 39 ClassFactory::RegisterClass(name, func); 40 }; 41 42 private: 43 ClassRegister() = delete; 44 }; 45 46 template<class T> 47 class ClassCreator { 48 public: NewInstance(const std::string & name)49 static T *NewInstance(const std::string &name) 50 { 51 return (T *)ClassFactory::NewInstance(name); 52 }; 53 }; 54 55 #define REGISTER_CLASS_CREATOR(class_name) \ 56 static void *class_name##Creator(void) \ 57 { \ 58 return (void *)(new class_name()); \ 59 } \ 60 const ClassRegister class_name##Register(#class_name, class_name##Creator) 61 } // namespace bluetooth 62 } // namespace OHOS 63 64 #endif // CLASS_CREATOR_H