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