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 OHOS_IPC_INVOKER_FACTORY_H 17 #define OHOS_IPC_INVOKER_FACTORY_H 18 19 #include <functional> 20 #include <unordered_map> 21 #include "iremote_invoker.h" 22 23 namespace OHOS { 24 #ifdef CONFIG_IPC_SINGLE 25 namespace IPC_SINGLE { 26 #endif 27 class InvokerFactory { 28 public: 29 using InvokerCreator = std::function<IRemoteInvoker *()>; 30 static InvokerFactory &Get(); 31 bool Register(int protocol, InvokerCreator creator); 32 void Unregister(int protocol); 33 IRemoteInvoker *newInstance(int protocol); 34 35 private: 36 InvokerFactory &operator = (const InvokerFactory &) = delete; 37 InvokerFactory(const InvokerFactory &) = delete; 38 InvokerFactory(); 39 ~InvokerFactory(); 40 static std::atomic<bool> isAvailable_; 41 std::mutex factoryMutex_; 42 std::unordered_map<int, InvokerCreator> creators_; 43 }; 44 template <typename T> class InvokerDelegator { 45 public: 46 InvokerDelegator(int prot); 47 ~InvokerDelegator(); 48 49 private: 50 int prot_; 51 InvokerDelegator &operator = (const InvokerDelegator &) = delete; 52 InvokerDelegator(const InvokerDelegator &) = delete; 53 }; 54 InvokerDelegator(int prot)55template <typename T> InvokerDelegator<T>::InvokerDelegator(int prot) 56 { 57 prot_ = prot; 58 auto invokerObject = []() -> IRemoteInvoker* { 59 auto data = new (std::nothrow) T(); 60 if (data == nullptr) { 61 return nullptr; 62 } 63 return static_cast<IRemoteInvoker *>(data); 64 }; 65 InvokerFactory::Get().Register(prot, invokerObject); 66 } 67 ~InvokerDelegator()68template <typename T> InvokerDelegator<T>::~InvokerDelegator() 69 { 70 } 71 #ifdef CONFIG_IPC_SINGLE 72 } // namespace IPC_SINGLE 73 #endif 74 } // namespace OHOS 75 #endif // OHOS_IPC_INVOKER_FACTORY_H