1 /* 2 * Copyright (c) 2023 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 INTELL_VOICE_GENERIC_FACTORY_H 17 #define INTELL_VOICE_GENERIC_FACTORY_H 18 #include <memory> 19 #include "refbase.h" 20 21 namespace OHOS { 22 namespace IntellVoiceUtils { 23 template <typename T> 24 class UniquePtrFactory { 25 public: 26 using UniqueProductPtr = std::unique_ptr<T, void (*)(T *)>; 27 28 template<typename ...Args> CreateInstance(Args &&...args)29 static UniqueProductPtr CreateInstance(Args && ...args) 30 { 31 T *instance = new(std::nothrow) T {}; 32 if (instance == nullptr) { 33 return UniqueProductPtr {nullptr, nullptr}; 34 } 35 if (!instance->Init(std::forward<Args>(args)...)) { 36 delete instance; 37 return UniqueProductPtr {nullptr, nullptr}; 38 } 39 return UniqueProductPtr(instance, DestroyInstance); 40 } 41 42 private: DestroyInstance(T * ptr)43 static void DestroyInstance(T *ptr) 44 { 45 delete ptr; 46 } 47 }; 48 49 template<typename T> 50 using UniqueProductType = typename UniquePtrFactory<T>::UniqueProductPtr; 51 52 template <typename B, typename D> 53 class SptrFactory { 54 public: 55 using SptrProductPtr = OHOS::sptr<B>; 56 57 template<typename ...Args> CreateInstance(Args &&...args)58 static SptrProductPtr CreateInstance(Args && ...args) 59 { 60 B *instance = new(std::nothrow) D {}; 61 if (instance == nullptr) { 62 return SptrProductPtr { nullptr }; 63 } 64 if (!instance->Init(std::forward<Args>(args)...)) { 65 delete instance; 66 return SptrProductPtr { nullptr }; 67 } 68 return SptrProductPtr(instance); 69 } 70 }; 71 72 template<typename B, typename D> 73 using SptrProductType = typename SptrFactory<B, D>::SptrProductPtr; 74 } 75 } 76 #endif 77