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