1 /* 2 * Copyright (c) 2025 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 FOUNDATION_ABILITY_RUNTIME_SIMULATOR_COMMON_BINDABLE_H 17 #define FOUNDATION_ABILITY_RUNTIME_SIMULATOR_COMMON_BINDABLE_H 18 19 #include <memory> 20 21 namespace OHOS { 22 namespace AbilityRuntime { 23 class Runtime; 24 25 class BindingObject final { 26 public: BindingObject(Runtime & runtime,T * ptr)27 template<class T> BindingObject(Runtime &runtime, T *ptr) : runtime_(runtime), object_(ptr, SimpleRelease<T>) {} 28 ~BindingObject() = default; 29 Get()30 template<class T> T *Get() 31 { 32 return static_cast<T *>(object_.get()); 33 } 34 Reset()35 void Reset() 36 { 37 object_.reset(); 38 } 39 Unbind()40 void Unbind() 41 { 42 if (object_) { 43 object_.release(); 44 } 45 } 46 GetRuntime()47 Runtime &GetRuntime() 48 { 49 return runtime_; 50 } 51 52 BindingObject(const BindingObject &) = delete; 53 BindingObject &operator=(const BindingObject &) = delete; 54 BindingObject(BindingObject &&) = delete; 55 BindingObject &operator=(BindingObject &&) = delete; 56 57 private: SimpleRelease(void * ptr)58 template<class T> static void SimpleRelease(void *ptr) 59 { 60 delete static_cast<T *>(ptr); 61 } 62 63 Runtime &runtime_; 64 std::unique_ptr<void, void (*)(void *)> object_; 65 }; 66 67 class Bindable { 68 public: 69 virtual ~Bindable() = default; 70 Bind(Runtime & runtime,T * object)71 template<class T> void Bind(Runtime &runtime, T *object) 72 { 73 object_ = std::make_unique<BindingObject>(runtime, object); 74 } 75 Unbind()76 void Unbind() 77 { 78 if (object_) { 79 object_->Unbind(); 80 } 81 } 82 GetBindingObject()83 const std::unique_ptr<BindingObject> &GetBindingObject() const 84 { 85 return object_; 86 } 87 88 protected: 89 Bindable() = default; 90 91 private: 92 std::unique_ptr<BindingObject> object_; 93 }; 94 } // namespace AbilityRuntime 95 } // namespace OHOS 96 #endif // FOUNDATION_ABILITY_RUNTIME_SIMULATOR_COMMON_BINDABLE_H 97